I’m using ajax to retrieve some data from the backend. I get the result as json.
I then use jquery to add it to the page:
$(...).append('<H3>' + data.title + '</H3>')
And I just realized that the json data is not HTML escaped, which is bad.
What should I do?
- HTML escape all the data returned from the backend in the json?
- Do all the escaping on the frontend when concatenating strings? (i.e. wrap all external data in an escaping function)
Option 1 means the data in the json is not really “correct”, it’s useful for HTML, but it does not contain the real data. And worse, it means I can’t just use json_encode() – I would first have to walk through the array data and escape everything.
Option 2 seems more complicated, and I’m worried I may miss a spot. On the other hand that’s what you do when getting data from SQL and building it in PHP, so I guess I’m used to it.
Please do not suggest:
$(...).append($('<H3></H3>').text(data.title))
That method of writing becomes unwieldy when you have many levels of nested tags. I like to write HTML, not DOM calls.
PS. I know I need a Javascript templating library, but for right now I need to do it with string concatenation.
Here is simple jQuery extension that adds
$append()formatting method with html escapement:With this method you can write:
And the data will be escaped. Add salt and pepper to the above – to your taste.
Update: You will also need this: