Reputation: 1401
I have an assoc array in PHP:
foreach ($result as $value) {
$x++;
$data += array("nds" => array($x => $x), "eds" => array(), "an" => array($x => $this->model->getLng($value)));
}
I send this array to a JS file and it prints like below:
{"nds":{"1":1},"eds":[],"an":{"1":[45.4423073,-75.7979993]}}
However, I cannot reach nds
because this returns undefined:
console.log(data.nds);
Upvotes: 0
Views: 100
Reputation: 47302
You can use the jQuery JSON parser or the standard Javascript JSON parser:
var data = '{"nds":{"1":1},"eds":[],"an":{"1":[45.4423073,-75.7979993]}}';
var d = $.parseJSON(data); // jQuery
console.log(d['nds']);
var j = JSON.parse(data); // Javascript
console.log(j['nds']);
example: http://jsfiddle.net/bb7ak6L5/
Upvotes: 0
Reputation: 20486
PHP is just sending a string to the JS file. You would first need to set a variable equal to that string:
<script>
var json = '<?= $data; ?>';
</script>
Now we have a JS variable json
, but it needs to be converted to an object to reference the nds
property. We can do that with JSON.parse()
:
<script>
var json = '<?= $data; ?>';
var data = JSON.parse(json);
console.log(data.nds); // Object {1: 1}
</script>
@RobM made a good point that we don't even need to parse this as a string and can just set the variable as the JSON dump:
<script>
var data = <?= $data; ?>;
console.log(data.nds); // Object {1: 1}
</script>
This still requires you to pass the JSON data ({ "nds": { "1": 1 }, "eds": [], "an": { "1": [ 45.4423073, -75.7979993 ] } }
) from your PHP script into a JS variable.
Upvotes: 1