Pushing a PHP array values into the JavaScript array?

5k views Asked by At

I am working with Blockly to make some Blocks. All the errors came up when I am making Blockly Blocks. IS there anyone who knows why my code is not working in Blockly?

I have a URL including a set of JSON code. I got the content in a myPhp.php file using:

$data = file_get_contents("URL");

and then, I decode the data using:

$objects = json_decode($data, true);

$objects contains:

[0] => Array
        (
            [name] => Light
            [x] => 5
            [h] => 5
            [y] => 5
            [status] => on
        )

Now I want to push this array of data into a JavaScript array using:

<script type="text/javascript">
    var obj = new Array();
    <?php 
     foreach($objects as $key => $value){ 
    ?>
    obj.push('<?php echo $value; ?>');
    <?php } ?>
</script>

And $value needs to have all those data.

But I am getting Invalid or unexpected token JavaScript error. and when I look at to the source code, it shows the error is related to this line: obj.push and it says obj.push('<br /> <b>Notice</b>: Array to string conversion in <b>myPhp.php</b> on line <b>20</b><br /> Array');.

3

There are 3 answers

7
Osama On BEST ANSWER

Your $value itself is an array and here your $key is 0.

$key

 [0] => 

$value

 Array
    (
        [name] => Light
        [x] => 5
        [h] => 5
        [y] => 5
        [status] => on
    )

So you need another loop for $value to obtain each value like thus

<script type="text/javascript">
 var obj = new Array();
<?php 
 foreach($objects as $key => $value){ 
   foreach($value as $key1 => $value1){
 ?>
 obj.push('<?php echo $value1; ?>');
 <?php } }?>
</script>
5
Jim On

Instead of going through the hassle of looping through the array or even decoding it (unless there is a specific reason to do so), just use json_encode. JSON is JavaScript's native language, so it will understand it.

<?php 
$data = json_decode(file_get_contents("URL"));
?><script type="text/javascript"><?php
    // echo out JSON encoded $data or a string of '[]' (empty JS array) if it is a false value (error occured with json_decode)
    ?>var obj = <?= json_encode($data) | '[]' ?>;<?php
    // In JavaScript "Light" is available as obj[0].name or it does not exist (empty array if an error occured with json_encode or json_decode)
?></script>
0
Arjan On

A few things to get you started:

  • JSON is "JavaScript Object Notation". Though it is used in many other languages, JavaScript understands it natively.

    This means that once you've got a JSON string, you can get a JavaScript object out of that directly. If the JSON string represents a single object, you'll get a single JavaScript object. If it represents an array, you'll get a JavaScript array of JavaScript objects. If it is some nested structure, then you'll get just that. In a modern browser all you need on the JavaScript side is JSON.parse(...) to do the magic.

  • To get the JSON into JavaScript, either:

    • Get it in JavaScript directly, using XMLHttpRequest or helpers such as jQuery's $.get. That will need you to understand some asynchronous programming, so maybe indeed one of the following is easier to start with:

    • Get it in PHP, parse it like you tried in your question, and then generate proper JavaScript to create a JavaScript object or array again. Note that PHP's json_decode gets you some associative array, which you then need to map to a JavaScript object.

    • Get it in PHP, do not parse it at all, and simply forward the JSON string to JavaScript and parse it there, using JSON.parse.

    • Get it in PHP, use Jim's simple solution to get it into JavaScript.

When generating JavaScript in PHP, you need to be careful with quotes, newlines and other special characters in string values. Like if the JSON is:

{"quote": "She said: 'Beware', and walked off"}

...then you cannot just concatenate text into obj.push('...') as that would create invalid JavaScript:

obj.push('She said: 'Beware', and walked off');

Above, JavaScript does not know what to do with the text after the second single quote, and throws Uncaught SyntaxError: missing ) after argument list. Likewise, newlines may be troublesome, like when unexpectedly getting a PHP error while generating the JavaScript (for reasons explained in Osama's answer), which will yield invalid JavaScript and throw Invalid or unexpected token:

obj.push('<br />
<b>Notice</b>: Array to string conversion
in <b>myPhp.php</b> on line <b>20</b><br /> Array');

In the JSON example above, you could use double quotes in obj.push("..."), to generate:

obj.push("She said: 'Beware', and walked off");

But in general you might not know what values you get, so you need to "escape" troublesome characters.

I don't know enough about PHP to know what's the best way to escape the strings. As (valid) JSON uses double quotes, it should already have escaped double quotes when needed. So, a JSON string might look like:

{"quote": "She said: \"Beware\", and walked off.\n\nWe'll remember her."}

Above, you need to take care of the backslashes that JSON already added for escaping. So PHP's addslashes might do, bus I did not test this:

<script type="text/javascript">
  var obj = JSON.parse("<?= addslashes($data) ?>");
</script>

Otherwise, when first parsing $data into a PHP object using json_decode (or when not even doing that!), Jim's simple solution is certainly preferred.