0

I am running a $.get call to get data from a php file:

 $.get("test.php", { home_type: home_info[0],  home_community: home_info[1] }, function(data) {
                        console.log(data);
 });

and it returns this data:

[{"id":"1", "title":"aaa"}, {"id":"2", "title":"bbb"}]

I tried to use a foreach method to use this data:

$.each(data, function (y, z) {
                                console.log(y);
                                console.log(z);
                        });

y returns a number starting at 1 and keeps counting up and z is each character in the data :( This is not what I was expecting. What do I have to get run a foreach and use each item at a time.

user979331
  • 11,039
  • 73
  • 223
  • 418
  • Your javascript is not evaluating your return data correctly as JSON data, and is instead treating it as a string. Try this instead: http://api.jquery.com/jquery.getjson/ – Mark Nov 04 '14 at 15:12
  • possible duplicate of [Can't get json data from jQuery ajax call](http://stackoverflow.com/questions/19475991/cant-get-json-data-from-jquery-ajax-call) – Mark Nov 04 '14 at 15:14
  • The y is the key of your array in the collection, and z is the object of that element. – vaso123 Nov 04 '14 at 15:15

3 Answers3

4
$.get("test.php", {

    home_type: home_info[0],
    home_community: home_info[1]

}, function (response) {

    var data = JSON.parse(response);
    $.each(data, function (index, value) {

        // Do something with each item...
        console.log(index);
        console.log(value);

    };

});
soulprovidr
  • 754
  • 3
  • 14
0

You need to convert your json string to object, just use parseJSON(data) and it will convert your to JSON object.

Strahinja Djurić
  • 394
  • 1
  • 2
  • 14
0

If you want access your data, try this:

var data = [{"id": "1", "title": "aaa"}, {"id": "2", "title": "bbb"}];
$.each(data, function(y, z) {
    console.log(z.id);
    console.log(z.title);
    //This is the same as
    console.log("Other way " + data[y].id);
    console.log("Other way " + data[y].title);
});

y is the array key of the current object in the array, while z is the object itself.

vaso123
  • 12,347
  • 4
  • 34
  • 64