HTML escaping data with ajax requests

If it is not HTML, it does not need HTML escaping, if it is not JS, it does not need JS escaping.

All escaping is context based. In general You should probably just avoid sending “text” in response and focus on sending data which is “converted” into whatever is the relevant DOM structures, either directly via DOM APIs or the roundabout ways jQuery offers. (in other words, your ajax response should be aimed at machines, and let the end machine to transform it to something which is readable by humans).

Still there are cases in which is more convenient to add full blown HTML texts to the response. If you go in that direction, the escaping should be relevant to how you are going to handle it on the browser side. jQuery’s html() expects a valid HTML therefore you will have to escape the textual parts of the HTML that you generate. DOM APIs might be more tolerant as depending on context they “know” what is an HTML tag and what is a text.

In any case I can’t think of any example in which you will have to do escaping on browser side. If you get yourself into such situation, you probably use the wrong DOM/jQuery APIs.

Commenting directly on your samples. The first one is wrong because if the text contains HTML tags, you will be escaping too much.