title: Prevent XSS in jQuery html()
body: <p>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:</p>
  
  <pre><code>$.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 &lt; messages.length; i++){
          result += 
              "&lt;div&gt;" + 
                  "&lt;p&gt;Name: " + messages[i].name + "&lt;/p&gt;" + 
                  "&lt;p&gt;Message: " + messages[i].message + "&lt;/p&gt;" + 
              "&lt;/div&gt;";
      }
      return result;
  }
  </code></pre>
  
  <p>Here is the getDatabaseData.php that gets and returns the data from the database:</p>
  
  <pre><code>$messages = $CFG_DB-&gt;select("SELECT name, message FROM messages");
  echo json_encode($messages);
  </code></pre>
  
  <p>Imagine for example if message contain the following text:</p>
  
  <pre><code>&lt;script&gt;XSS Attack code goes here&lt;/script&gt;
  </code></pre>
  
  <p><strong>My questions are:</strong></p>
  
  <ol>
  <li>Will there be an XSS issue when doing like this?</li>
  <li>In case there is an issue, how can I prevent it?</li>
  </ol>
  
  <p>I guess that using text() instead of html() is not an option in this case since I also add html code.</p>
  
  <p>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.</p>