0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

in this case I get: Uncaught TypeError: Cannot read property 'length' of undefined
This (var json = '<?= $data; ?>';) is not necessarily valid, how have you outputted the JSON string from PHP in your current code? My code assumes that the PHP variable $data is passed to your JS code.
{ "nds": { "1": 1 }, "eds": [], "an": { "1": [ 45.4423073, -75.7979993 ] } }
For my above code to work, you need to have the following line of JS: var json = '{ "nds": { "1": 1 }, "eds": [], "an": { "1": [ 45.4423073, -75.7979993 ] } }';. Depending on your set up, this should be pretty easy. But we can't do any JS parsing until the string is a JS variable.
Why not just omit the quotes? Then you won't have to JSON.parse
|
0

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/

1 Comment

Is it possible to make it accessible for something like that console.log(j.nds[0]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.