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

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.

3 Answers
3

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.
Tags:

Leave a Reply

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