title: Is it safe to use eval in javascript when it only executes server-side data?
body: <p>Yes, it's a kinda duplicate of <a href="https://stackoverflow.com/questions/6727365/is-using-eval-for-data-from-only-server-side-safe-and-if-not-alternatives-p">this question</a>, but the answer given by @apsillers is a super-answer as it points a new aspect of the problem that have not been told in the previous question. Another helpful SO question that helped me to undestand better what exactly are the eval() security concerns is <a href="https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea">that question</a></p>
  
  <p>I use eval() in my javascript code and I'm wondering if I should let it down. </p>
  
  <p>Principe : I have an ajax call which initialize the first connexion between a browser client and the server. The server runs PHP. The rules is : when the client send the variable 'init' in request, on server side PHP get the contents of necessary scripts, put the content of each script as a new entry in an object (the value is the content, the name is the filename without the extension and the object is an instance of PHP STD Class), convert the whole object in JSON (by convention) and send back everything. On the client side, when the httprequest is done, Javascript get the object and do a simple for ... in () on it. </p>
  
  <p>On each occurence, I have two choice : either I concat the content into a craft-made script tag and I inject it into the <em>head</em> of the HTML page. Or I eval the content (which I do now) in order to execute the code without surcharging the <em>head</em> tag. It's mostly for aesthetic.</p>
  
  <p>Here is the code : </p>
  
  <pre><code>var xhr = null;
  
  if (window.XMLHttpRequest || window.ActiveXObject) {
      ... //prepare the ajax request (initialize variable xhr)
  }
  
  
  var url = "index.php";
  var params = "action=init";
  xhr.open('POST', url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(params);
  
  xhr.onreadystatechange = function() {
         if (xhr.readyState == 4 &amp;&amp; (xhr.status == 200 || xhr.status == 0)) {
             var o = JSON.parse(xhr.responseText);
  
  
             for(s in o) eval(o[s]);
  
  
         }
  }
  </code></pre>
  
  <p>My question : should I definitely avoid to use eval in this situation? Or is it safe enough (since only administrators are able to modify the scripts which are dynamically injected) ?</p>