I'm looking for a way to prevent XSS in my pure javascript platform which calls a PHP API that returns JSON data using json_encode().
Take this basic example:
<script>alert('hello world');</script>
Let's say the above is stored in a database field which is grabbed by PHP and returned to the browser using json_encode():
<?php
echo json_encode(array('name'=>"<script>alert('hello world');</script>"), JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
?>
As you can see, i've used a few json options in hopes this would sanitize the data for javascript usage. However, when I do the following in JavaScript, the alert still executes:
<script>
$('.nameField').html(jsonData.name);
</script>
From what i've read, the json options are the best practice for json_encoded data, but yet it still executes.
Where am I going wrong?