HTML escaping data with ajax requests

Question

I follow the WP philosophy of late escaping, but I’m not sure when to escape HTML special characters when working with ajax requests.

Note, as of my understanding, when setting data to an element with the jQuery .text() method, or using createTextNode()` method, it automatically escapes text content. So this question doesn’t apply to using those methods.

When setting text content to an element with innerHTML property or jQuery .html() method after an ajax request, is it better to escape the text content with js, or is it better to escape the text content on the server side with esc_html()?

Here are two examples, I’m not sure what the best one is:

Escapaing server side before sending to client:

// PHP

// Final stage of processing the ajax request (server side).
echo esc_html($text);
die();


//JS (jQuery)

// Final stage of a JS ajax request
success: function(response) {
    $('.example').html('<div class="example">' + response + '</div>'); // The response is already escaped
}

Or Escaping with JS after the ajax request was successful:

// PHP

// Final stage of processing the ajax request (server side).
echo $text;
die();


//JS (jQuery)

/**
 * Example of my js html escape function
 */
function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "'");
 }

//Final stage of a JS ajax request
success: function(response) {

    // Escape the untrusted data
    $('.example').html('<div class="example">' + escapeHtml(response) + '</div>'); // The response needs to be escaped
}

Any help appreciated.

0
user3438958 2 years 2020-10-22T03:10:24-05:00 0 Answers 6 views 0

Leave an answer

Browse
Browse