title: Should I use <script> tag to pass data from PHP to JavaScript?
body: <p>The accepted answer to <a href="https://stackoverflow.com/questions/23740548">"How to pass variables and data from PHP to JavaScript?"</a> lists a number of methods. One that isn't explicitly mentioned (although it fits under method 2) is discussed in <a href="https://stackoverflow.com/questions/7581133">"How can I read a JSON in the script-tag from JavaScript?"</a>. It works by using the PHP function (copied from <a href="https://mathiasbynens.be/notes/json-dom-csp#script" rel="nofollow noreferrer">Mathias Bynens</a>)</p>
  
  <pre><code>json_encode($data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)
  </code></pre>
  
  <p>to write the content of a tag such as</p>
  
  <pre><code>&lt;script id="data" type="application/json"&gt;{org: 10, items:["one","two"]}&lt;/script&gt;
  </code></pre>
  
  <p>(copied from <a href="https://stackoverflow.com/a/7956249/4166379">the answer</a> of <a href="https://stackoverflow.com/users/421163/c-smile">c-smile</a>), which is then read from the DOM by JavaScript.</p>
  
  <p>This seems to be the best method for my case (I would rather not do a separate AJAX call), but I'm slightly concerned that it doesn't seem to be standard way of doing these things. Are there potential security issues I should be aware of?</p>
  
  <p>And is this likely to be reasonably future-proof? Is it possible that there will be changes to the <code>&lt;script&gt;</code> tag or the way that browsers handle <code>type="application/json"</code> that will break this approach?</p>
  
  <hr>
  
  <p><strong>Update</strong></p>
  
  <p>Here's an example of the approach:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script id="data" type="application/json"&gt;
  &lt;?php 
  $data = array(
      "org" =&gt; 10,
      "items" =&gt; array("one", "two"),
      "backslash" =&gt; "\\",
      "slash" =&gt; "/",
      "single quote" =&gt; "'",
      "double quote" =&gt; "\"",
      "close tag" =&gt; "&lt;/script&gt;"
  );
  echo json_encode($data, JSON_HEX_TAG);
  ?&gt;
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;script&gt;
  var data = JSON.parse(document.getElementById("data").innerHTML);
  
  for(var key in data) {
      if(data.hasOwnProperty(key)) {
          var p = document.createElement("pre");
          document.getElementsByTagName("body")[0].appendChild(p);
          p.appendChild(document.createTextNode(data[key].toString()));
      }
  }
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>