Bram Vanroy Bram Vanroy - 7 months ago 11
Javascript Question

Why don't I have to decode/parse a JSON string generated by PHP in JS

To use some variables in a JS script, I simply set them in a wrapper with JSON, like so:

<?php // Variables for JS
$vars = array(
'fetchPath' => "$home/my-url.php",
);
?>
<script>
var phpVars = <?php echo json_encode($vars); ?>;
</script>


This results in

<script>
var phpVars = {"fetchPath":"http:\/\/my.website.com\/my-url.php"};
</script>


Now, when I try to parse this value from a JS script, I get an unexpected token error. But, when I simply use the variable as if it were an object, it works perfectly. In other words, I can simply access
phpVars.fetchPath
without having converted that value back to an object representation.

Am I completely losing my mind after hours of working with Perl, PHP, and Javascript, and you don't have to decode a JSON string in JS - or is something else going on?

Answer

When you do this:

<script>
var phpVars = <?php echo json_encode($vars); ?>;
</script>

you're generating JavaScript code with PHP. So what actually goes to your browser is:

<script>
var phpVars = /*...THE_JSON_GOES_HERE...*/;
</script>

Note that it's not in quotes or anything. Your example code will produce a JSON string that looks something like {"fetchPath":"/path/to/my-url.php"}, so what the browser would see is:

<script>
var phpVars = {"fetchPath":"http:\/\/my.website.com\my-url.php"};
</script>

Since JSON is a subset of JavaScript object initializer syntax, that's perfectly valid JavaScript code. The parser parsing the script tag contents parses it as code, not as JSON. But that's fine, because as long as it's used as a right-hand value (e.g., on the right-hand side of = or passed into a function, etc.), JSON is valid JavaScript.

Comments