Reputation: 459
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:
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.
Upvotes: 1
Views: 8881
Reputation: 171669
Setting text with user input is the safest way. Instead of creating html strings, create elements instead
Something like:
function getMessagesHtml(messages){
return messages.map(function(o){
var $div = $('<div>');
$div.append($('<p>', {text: "Name: " + o.name}));
$div.append($('<p>', {text: "Message: " + o.message}));
return $div;
});
}
Per comments an alternative is create a sanitizing helper function that creates an element that passes the input string as text to the element and returns that text
function text(str){
return $('<div>',{text:str}).text();
}
Upvotes: 4