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) );
}

1
1

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) );
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *