47

I'm trying to loop through this to get the 'name' values. This is what I currently have, but it doesn't seem to be working, tried a few others from what was posted here but nothing seemed to work.

    $.get("/get_names", {campaign_id: $('select[name="id"]').val()}, 
                function(data){
                    $.each(data, function(i, item) {
                        alert(item);
                    });
                }
   );

Json being returned:

   [
           {
              "name":"age"
           },
           {
              "name":"asdf"
           },
           {
              "name":"drivername"
           },
           {
              "name":"drivers"
           },
           {
              "name":"firstname"
           },
           {
              "name":"gender"
           },
           {
              "name":"lastname"
           },
           {
              "name":"make"
           },
           {
              "name":"model"
           },
           {
              "name":"vehicles"
           },
           {
              "name":"year"
           }
        ]

I've tried using:

item.name
item[i].name

Any suggestions?

Thank you!

2
  • returns a single bracket, '['
    – dzm
    Oct 14, 2011 at 18:03
  • that means it's not treating it as an array...
    – jackJoe
    Oct 14, 2011 at 18:04

3 Answers 3

132

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});
2
  • 2
    that is that i wrote below :)
    – Royi Namir
    Oct 14, 2011 at 18:06
  • But doesn't this make the script async??
    – ruveena
    Oct 5, 2015 at 9:37
11

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

1

I dont think youre returning json object from server. just a string.

you need the dataType of the return object to be json

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.