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?
PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
The json_encode() function is used to encode a value to JSON format.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With