I receive data from a database using ajax and then adds it together with HTML code to the website using the .html() jQuery function, like this:
$.ajax({
url: "getDatabaseData.php",
type: "post",
dataType: "json",
success: function(response){
$("#message-div").html(getMessagesHtml(response));
}
});
function getMessagesHtml(messages){
var result = "";
for(var i = 0; i < messages.length; i++){
result +=
"<div>" +
"<p>Name: " + messages[i].name + "</p>" +
"<p>Message: " + messages[i].message + "</p>" +
"</div>";
}
return result;
}
Here is the getDatabaseData.php that gets and returns the data from the database:
$messages = $CFG_DB->select("SELECT name, message FROM messages");
echo json_encode($messages);
Imagine for example if message contain the following text:
<script>XSS Attack code goes here</script>
My questions are:
- Will there be an XSS issue when doing like this?
- In case there is an issue, how can I prevent it?
I guess that using text() instead of html() is not an option in this case since I also add html code.
Without javascript, when printing the data using PHP I just use htmlentities on the variables received from the database to prevent XSS, for example htmlentities(messages[i].name) and htmlentities(messages[i].message). But I have not seen any similar for javascript.