Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
roverred Avatar asked Aug 30 '13 08:08

roverred


People also ask

What is Echo json_encode in PHP?

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.

What is json_encode and Json_decode?

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.

What is json_encode used for?

The json_encode() function is used to encode a value to JSON format.


1 Answers

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 );
like image 167
Kashinath Patil Avatar answered Oct 21 '22 19:10

Kashinath Patil