What is correct way to send HTML back to an AJAX request in WordPress?

I currently have this:

add_action( 'wp_ajax_nopriv_get-location-info', 'sc_locations_get_location_info' );
add_action( 'wp_ajax_get-location-info', 'sc_locations_get_location_info' );
function sc_locations_get_location_info() {
    $nonce = $_POST['nonce'];
    if ( ! wp_verify_nonce( $nonce, 'get-location-info-nonce' ) ) {
        $response = json_encode( array( 'success' => false, 'error' => "Failed nonce check" ) );
    } else {
        $response = json_encode( array( 'success' => true, 'HTML' => '...LOTS OF WONDERFUL HTML...' ) );
    header( "Content-Type: application/json" );
    echo $response;

Now I'm currently just using json_encode() but should I be doing anything else to the HTML? The HTML generated can be trusted so no stripping would need to take place.

  • Could you recommend a tutorial that explains in more details about json_encode and how to use it in context of ajax and WP? I'm getting confused with things that I found and there isn't a really good example and explanation on how to return an HTML snippet back to JS script. – dashaluna Apr 1 '14 at 15:05

Depending on what kind of HTML you're expecting, there are different tools you can use:

  • esc_html() escapes entire HTML blocks so you don't end up with breaking characters in your JSON object literals.
  • esc_html_e() escapes (as above) and translates the string if you're concerned about localization in that context.
  • wp_kses() will parse the HTML string and strip out any "evil" (explicitly disallowed) tags.
| improve this answer | |
  • @EAMann just the answer I was looking for. I will use wp_kses as some of the code comes from the editor. I know it can be trusted but I'll run it just in case. – Scott Feb 14 '12 at 9:28

If the HTML is fully trusted, I'd say no additional processing needs to be done, though theoretically it might be better to send the data in parts and use JS DOM to create your HTML...depends on the weight of each way of doing it...and I suppose whether you want a single, probably heavier, load up front w/ lighter bandwidth usage from the AJAX or if you want lighter load up front with multiple heavier loads from the AJAX.

| improve this answer | |
  • The HTML returned isn't that much maybe I was exaggerating a bit when I said LOTS OF WONDERFUL HTML. What about dealing with entities? – Scott Feb 13 '12 at 17:23
  • @Brady How do you mean? – mor7ifer Feb 13 '12 at 17:50

You can use WordPress native - WP_Ajax_Response

| improve this answer | |
  • 1
    Sorry but this is of no use. I'm using a JSON response not XML. – Scott Feb 14 '12 at 9:25

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.