Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass php array of arrays to Javascript

I have an array of arrays in PHP in this layout for example,

"Key1" => { "id" => 1, "name" => "MyName", "address" => "USA" }
"Key2" => { "id" => 2, "name" => "MyName2", "address" => "Australia" }

The data in the PHP array was taken from SQL Database. Now I want to be able to use this in JavaScript.

I searched the web and people are suggesting to use JSON using this code:

var js_var = JSON.parse("<?php echo json_encode($var); ?>");

I get this error in firefox when using firebug

missing ) after argument list [Break On This Error]
var js_var = JSON.parse("{"Key1":{"id":"1","name":"MyName","address":"USA"...

Error is in right after JSON.parse("{"Key1

In google chrome, firebug does not report any errors

like image 680
John Ng Avatar asked Oct 24 '25 04:10

John Ng


1 Answers

var js_var = JSON.parse('<?php echo json_encode($var); ?>');

Or, even better:

var js_var = <?php echo json_encode($var); ?>;

... Since JSON is, by definition, valid JavaScript syntax for object declaration.

like image 102
greyfade Avatar answered Oct 26 '25 18:10

greyfade