The accepted answer to "How to pass variables and data from PHP to JavaScript?" lists a number of methods. One that isn't explicitly mentioned (although it fits under method 2) is discussed in "How can I read a JSON in the script-tag from JavaScript?". It works by using the PHP function (copied from Mathias Bynens)
json_encode($data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES)
to write the content of a tag such as
<script id="data" type="application/json">{org: 10, items:["one","two"]}</script>
(copied from the answer of c-smile), which is then read from the DOM by JavaScript.
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?
And is this likely to be reasonably future-proof? Is it possible that there will be changes to the <script> tag or the way that browsers handle type="application/json" that will break this approach?
Update
Here's an example of the approach:
<html>
<head>
<script id="data" type="application/json">
<?php
$data = array(
"org" => 10,
"items" => array("one", "two"),
"backslash" => "\\",
"slash" => "/",
"single quote" => "'",
"double quote" => "\"",
"close tag" => "</script>"
);
echo json_encode($data, JSON_HEX_TAG);
?>
</script>
</head>
<body>
<script>
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()));
}
}
</script>
</body>
</html>
"</script>"inside your data, other than that it seems like a pretty good solution.