I\'m trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I\'m wondering why pass the JSON from PHP to javasc
In your case $json_obj
is already a string. So it is not necessary. But if you have an array you want to pass to javascript json_encode
will help you with this.
Usually this is what I do, the safest way I've found:
// holds variables from PHP
var stuff = {};
try {
// stuff will always be an object
stuff = JSON.parse('<?php echo empty($stuff) ? '{}' : json_encode($stuff) ?>');
} catch (e) {
if (e instanceof SyntaxError)
{
// report syntax error
console.error("Cannot parse JSON", e);
}
}
// show resulting object in console
console.log("stuff:", stuff);
Passing PHP JSON to Javascript and reading
var stuff = <?php print json_encode($datajson); ?>;
var arr = new Array();
arr= JSON.parse(stuff);
document.write((arr[0].cust_code );
json_encode
is a function that converts a PHP array into a JSON string, and nothing more. Since your $json_obj
variable is already a JSON string, no further conversion is needed and you can simply echo it out.
To get to your $json_obj
string from an array your code would have looked like this
$json_array = array(
"const1" => "val",
"const2" => "val2"
);
$json_obj = json_encode($json_array);
Even though it may seem like overkill for your particular problem, I would go for the json_encode/parse option still. Why? you ask. Well, think of it as avoiding duplication. If you encode/parse you can keep the constants in an object easily readable by you PHP-code. And the same for your JS code.
It simply eliminates the need to fiddle with it.
The argument to json_encode()
should be a PHP data structure, not a string that's already in JSON format. You use this when you want to pass a PHP object to Javascript.