Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
You use json_encode on arrays and objects, what you have there is just a string, not need to encode it. –  slash197 Aug 30 '13 at 8:51
    
What if the variable you want to store your data on client side changes its name? What if you want to use the same data on multiple occasions? What if something already is stored in the global variable json? ... –  Sirko Aug 30 '13 at 8:52
    
if you have an array or even an object, like stdClass object, it is easier to use json_encode then to loop through the array/object to print out the contents. –  Patrick Evans Aug 30 '13 at 8:53

9 Answers 9

up vote 2 down vote accepted

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.

share|improve this answer

It all depends on what you want to send from server to the client - be it a data (JSON) or some code.

Two approaches:

  1. Echo a JSON file on a server - then you print your JSON document and set response Content-Type to application/json. This way you can use any AJAX library you wish, like $.get or raw XMLHttpRequest etc. It is a way of passing data.

  2. 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.

share|improve this answer

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.

share|improve this answer

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 );

share|improve this answer

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\"}"
share|improve this answer

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.

share|improve this answer

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);
share|improve this answer

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, ....
share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.