John Ng
John Ng

Reputation: 899

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

Upvotes: 4

Views: 2623

Answers (3)

James
James

Reputation: 2669

Your error is being cause by the fact you are using double-quotation marks (") to wrap the JSON string. Due to the fact that the JSON string also contains double-quotations the parser is unable to determine when the string starts and ends correctly.

Change the line to this:

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

That been said JSON or JavaScript Object Notation is already a subset of the JavaScript programming language and therefore can already be parsed by the JavaScript engine so does not necessarily need to be parsed by JSON.parse.

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

I would however only recommend this option if you are sure about the JSON you are outputting as an incorrect parsing by JSON.parse can be handled where as incorrect JSON injected directly will cause a parser error I believe.

Upvotes: 2

user1207456
user1207456

Reputation:

Why go through this bizarre json_encode into a string to only JSON.parse on the client side? Useless use of encoding, really.

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

Upvotes: 2

greyfade
greyfade

Reputation: 25677

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.

Upvotes: 5

Related Questions