title: How to safely XSS encode untrusted data coming from PHP through AJAX injected into the DOM via javascript?
body: <p>I felt pretty confident with XSS prevention with an older setup we had on our site ... we were using OWASP's XSS mitigation functions for stroking out user supplied data from a database (we inject values into DB directly via prepared statements, no encoding takes place till output time) and printing it via (simplified for readability):</p>
  
  <h2>show.php</h2>
  
  <pre><code>print "&lt;li&gt;";
  print "&lt;a href='page?id=".xssafe($row-&gt;TRUSTED_VALUE)."'&gt;".xssafe($row-&gt;UNTRUSTED_VALUE)."&lt;/a&gt;";
  print "&lt;/li&gt;";
  </code></pre>
  
  <p>For numerous reasons, scalability, pagination, flexibility, we're switching to an AJAX oriented scheme.  Instead of printing out these LI blocks directly, we AJAX them in immediately on page load (technically $(document).ready()) and let the client via javascript &amp; jQuery handle everything. I'm concerned about this approach as I've read a ton on the subject and am still not confident in how to maintain XSS security.</p>
  
  <p>Our new setup is this:</p>
  
  <h2>retrieve.php (I originally still had the xssafe() wrappers, but read that I should just use json_encode())</h2>
  
  <pre><code>$data['TRUSTED_VALUE'] = $row-&gt;TRUSTED_VALUE; // 123
  $data['UNTRUSTED_VALUE'] = $row-&gt;UNTRUSTED_VALUE; // who knows?
  header('Content-Type: application/json');
  print json_encode($data);
  </code></pre>
  
  <h2>show.php</h2>
  
  <pre><code>&lt;script src="show.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <h2>show.js</h2>
  
  <pre><code>$.ajax({
          url: 'retrive.php',
          dataType: 'json',
          data: {page: pageNum},
          success: loadLI
  }); 
  
  function loadLI() {
          data = response.data;
          var li = document.createElement('li');
          var anchor = document.createElement('a');
          anchor.setAttribute('href', 'page?id='+encodeURIComponent(data.TRUSTED_VALUE));
          anchor.appendChild(document.createTextNode(data.UNTRUSTED_VALUE));
          li.appendChild(anchor);
  
  }
  </code></pre>
  
  <p>Should I keep the xssafe() wrapper functions in our retrieve.php script, then json_encode, then inject those values via Javascript?  Or is our new setup safe?  Or is there a better way to do this? Thanks.</p>