4

I don't understand how to return HTML correctly via AJAX.

I have this routine

function DisplayEventInfoBox()
{    ?>
    <div id="eventInfo">
    <div class="avail-from cart-right">

    <?php   
    and so on...
}

If I include this in an AJAX call and the end of the routine is a die() the response object contains the HTML, which I can use as I like.

function myAJAXFn() {
    DisplayEventInfoBox($my_page, $shipHelper);
    die();
}

I want to send additional information, for instance using wp_send_json_success or another variable.

This code returns the HTML with the JSON array tacked on to the end. I would like a create a JSON object where I can access my page property and the html. What's the best way to do this?

function myAJAXFn() {
    DisplayEventInfoBox($my_page, $shipHelper);
    wp_send_json_success( array('page'=>$myPage) );
}
3

I can't tell what the $my_page, $my_page, or $shipHelper variables are supposed to do, but you can use an output buffer to capture the output of your DisplayEventInfoBox function. You can try the following:

function myAJAXFn() {
    ob_start();
    DisplayEventInfoBox($my_page, $shipHelper);
    $my_html = ob_get_contents();
    ob_end_clean();
    wp_send_json_success( array('page'=>$my_html) );
}
  • Yes that's what I was looking for. I've also read a better way may be to split the ajax into two calls for presentation and data. – strattonn Mar 18 '15 at 3:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.