jquery - How to select ajax response to use in colorbox javascript? -
i have ajax function outputs results of +1 , -1, in javascript, want +1 response use in colorbox. ajax function:
function my_ajax_obj_lightbox() { global $post; if ( !empty( $_post['obj_id'] ) ) { $obj = new my_obj( $_post['obj_id'] ); if ( $obj instanceof my_obj ) { my_objs_ajax_response_string( 1, $obj->html() ); } } my_objs_ajax_response_string( -1, 'invalid request' ); } add_filter( 'wp_ajax_obj_lightbox', 'my_ajax_obj_lightbox' );
now , in javascript, want this:
var response = ......; if ( response[0] >= 1 ) { j.fn.colorbox({ html: response[1], maxwidth: '90%', maxheight: '90%' }); }
how define var response , ajax response value ?
it sounds need setting ajax request, , parsing response javascript object...
let's have php file returns response in json format:
<?php header('content-type: application/json'); ?> [1, "<h2><?php echo $_post['title'] ?></h2>"]
to retrieve using ajax, can this:
<script> // create ajax request object. var request = new xmlhttprequest(); // define function handle response. request.onreadystatechange = function() { // if response ready if (request.readystate == 4 && request.status == 200) { // transform response javascript object. var response = eval(request.responsetext); /* "response" javascript array containing 2 values. */ console.log(response[0]); /* 1 */ console.log(response[1]); /* <h2>hello world</h2> */ // write contents of response element on page. if (response[0] >= 1) { var div = document.createelement("div"); div.innerhtml = response[1]; document.body.appendchild(div); } } }; // define variables want send server. var params = "foo=bar&baz=qux&title=" + encodeuricomponent("hello world"); // post data, , load response asynchronously. request.open("post", "/ajax-response.php", true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send(params); </script>
if you're using jquery, here's equivalent code:
<script> $.post("/ajax-response.php", { foo: "bar", baz: "qux", title: "hello world" }, function(response) { if (response[0] >= 1) { $("body").append(response[1]); } } ); </script>
documentation jquery post: http://api.jquery.com/jquery.post/
Comments
Post a Comment