Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent XSS in javascript on data received by ajax

I receive data from a database and adds the result to an HTML element using jQuery ajax like this:

$.ajax({
    url: "getDatabaseData.php",
    type: "post",
    dataType: "json",
    success: function(response){
        $("#message-div").html(response[0].user_input_message);
    }
});

Here is the getDatabaseData.php that gets and returns the data from the database:

$messages = $CFG_DB->select("SELECT user_input_message FROM messages");
echo json_encode($messages);

Imagine for example if user_input_message contain the following text:

<script>XSS Attack code goes here</script>

My questions are:

  1. Will there be an XSS issue when doing like this?
  2. In case there is an issue, how can I prevent it?

Without ajax, when printing the data using PHP I just use htmlentities to prevent XSS, but I have not seen any similar for javascript.

like image 567
Danie Avatar asked Mar 28 '26 13:03

Danie


1 Answers

when printing the data using PHP I just use htmlentities to prevent XSS

The equivalent is to use text() instead of html().

like image 81
Quentin Avatar answered Mar 30 '26 03:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!