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.
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.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.
You can use WordPress native – WP_Ajax_Response