Skip to content
Advertisement

How do I access a JSON array in JavaScript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I’m having trouble accessing an array in the data returned to the JavaScript function.

So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:

JavaScript

A relevant excerpt of the PHP script is:

JavaScript

In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.

JavaScript

… and the console will display what I’m expecting, namely:

JavaScript

However, I’m having difficulty accessing these values. For example, supposing I try to access the “815” portion of the first element, with something like: myArray[0][1], all I end up with is “[“.

I guess somehow this whole piece of data is just a string, instead of an array, but I’m not familiar enough with JavaScript to quite know how to progress.

If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I’ll see is the single alert with “[“. (i.e. it does the loop only once, and selects the character in position 1).

JavaScript

I would very much appreciate someone explaining: (a) how I can access the individual elements and values in JS (b) how I can loop through them, although presumably once it’s an array and not a string then the code above should do this.

Many thanks for any assistance.

Now Resolved: As noted by @charlietfl, below, using quotes in

JavaScript

screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.

So, the original snippet of code, given above, now looks like:

JavaScript

Advertisement

Answer

Change

JavaScript

To

JavaScript

And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement