loop through Object in Javascript get from PHP

310

Hello I have a PHP script that returns the following JSON :

[
    {
        "zone_name": "1st_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    },
    {
        "zone_name": "2nd_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152",
            "51.57707,0.11398",
            "51.48651,0.12497",
            "51.56939,0.28427"
        ]
    }
]

In Javascript I'm doing an AJAX call like that :

$.ajax({
        type: "POST",
        cache: false,
        url: "load_zone.php",   
        dataType: 'json',
        success:function(response){
            for(var i =0; i<response.length; i++){
                console.log(response[i]);
            }
        },
        error:function(){
        }
    }); 

I get this result in console :

Object { zone_name="1st_zone"}
Object { coordinates=[5]}
Object { zone_name="2nd_zone"}
Object { coordinates=[8]}

How can I print each zone_name and coordinates separately?

Thanks

140

Answer

Solution:

for(var i =0; i<response.length; i++){
   if(i%2 === 0) console.log(response[i].zone_name);
   else console.log(response[i].coordinates); 
  // console.log(response[i].zone_name || response[i].coordinates); //one liner
}

This will give you the respective zone names and coordinates. Your current JSON has an array of objects which list the zone names and coordinates as successive elements of the array.

But you should try to change your json to look something like this:

[
    {
        "zone_name": "1st_zone"
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    }
...
]

Which will mean that the array would contain objects representing a zone with its coordinates. Which can then be accessed likeresponse[i].zone_name andresponse[i].coordinates.

672

Answer

Solution:

do like this:

$.each(data,function(index,item){

    console.log(item);
    $.each(item,function(index1,item1){
    console.log(item1);
    });

People are also looking for solutions to the problem: php - how to let each user page show different information based on input on the user page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.