'Passing PHP JSON to Javascript: echo json_encode vs echo json declaration
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 javascript using json_encode()
over echoing the json declaration.
Let's say I have the PHP JSON
<?php
$json_obj = '{"const1": "val",
"const2": "val2"
}';
?>
Googling, it seems the typical way of passing back to javascript is using
<?php echo json_encode($json_obj); ?>
Then I believe I would have to use something like $.getScript()
to read the php file to get $json_obj
and then use parseJSON()
to make it useable in javascript.
But why not instead
<?php echo 'var json = '.$json_obj; ?>
This way all you have to do is load the script directly and you have the json ready to use directly.
Is there a particular reason why it is more favorable to use json_encode()
then simply echoing the declaration to javascript?
Solution 1:[1]
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.
Solution 2:[2]
It all depends on what you want to send from server to the client - be it a data (JSON) or some code.
Two approaches:
Echo a JSON file on a server - then you print your JSON document and set response
Content-Type
toapplication/json
. This way you can use any AJAX library you wish, like$.get
or rawXMLHttpRequest
etc. It is a way of passing data.Echo a Javascript code on a server and then use
$.getScript
to load it. It's a way of passing code. This is potentially less secure, because your code can contain not only JSON, but also any arbitary code. So if attacker can compromise your server, he could be able to push code to any client for a remote execution.
If you want to pass data only, go with first approach. It's cleaner and more safe.
Additionally, if you ever end up writing frontend in different environment, say different programming language, you'll be able to resuse the same JSON-returning endpoint. It'll be harder if you return Javascript code.
Solution 3:[3]
Passing PHP JSON to Javascript and reading
var data = <?php echo json_encode($json); ?>;
var arr = new Array();
arr = JSON.parse(data);
document.write( arr[0].something );
Solution 4:[4]
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.
Solution 5:[5]
constant.php
<?php
$array = array("const1" => "val", "const2" => "val2");
?>
<script>
var contants = <?php echo json_encode($array); ?>
</script>
======================END OF FILE constant.php=======
In php you can access using
$array["<key>"]
In javascript, you can access using
contants.const1, ....
Solution 6:[6]
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);
Solution 7:[7]
You use json_encode
if you use php array not a string:
$array = array("const1" => "val", "const2" => "val2");
echo json_encode($array);
if you call json_encode on a string you will get:
"{\"const1\": \"val\", \"const2\": \"val2\"}"
Solution 8:[8]
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.
Solution 9:[9]
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);
Solution 10:[10]
PHP To JSON
var locations = <?php echo json_encode($sample_location_master); ?>;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow