'Html and Javascipt escaping

I'm using laminas-escaper for escaping values in html and javascript. I fetch values from the server using ajax. So I escape them in php using laminas-escaper. When i fetch the data from server I store them in a js variable and sometimes even display them using html. For example in sample.js:

var xhttp   = new XMLHttpRequest();
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader("Content-Type", "application/json"); 
xhttp.onreadystatechange=function()
{
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        var response = JSON.parse(xhttp.responseText);
        var name = response.name;
        document.getElementById('demo').innerHTML = name;
    }
}
xhttp.send();

The response came from the server will be in json format. For example : '{name:xxx,address:yyy}'

My question is should i only use $escaper->escapeJs($input) for escaping js, or only use $escaper->escapeHtml($input) for html escaping or use both. If I have to use both then in which order.

Note: I perform escaping in server and send the result to the browser.



Solution 1:[1]

You should escape the data, at the last possible moment, in a fashion suitable for what you are injecting it into.

If you are returning JSON to the browser then you should let PHP's json_encode function do the escaping for you.

If you are returning HTML to the browser then your PHP should escape the data for insertion in HTML.

If you're injecting the data into JavaScript embedded in the middle of an HTML document and then returning the HTML to the browser, then your PHP should escape it for both JS and HTML.

If you're turning plain text to the browser then you shouldn't escape it with the PHP at all. If the browser then goes on to insert the returned text into the DOM with client-side JS then any escaping that needs doing is something that should be done by the client-side JS.

Likewise if you're returning JSON that the client-side JS parses and then inserts into the HTML then the PHP should handle any escaping for the JSON and the client-side JS should handle any escaping for the HTML.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin