JSON iteration as part of $ .ajax success

When the user clicks the button, I want to return some data and iterate through JSON to add the results to the table.

At this point, I'm just trying to get my loop to work, here is my code.

My JSON is returned as follows: {"COLUMNS": ["username", "password"], "DATA": [["foo", "bar"]]}

$("#button").click(function(){ $.ajax({ url: 'http://localhost/test.php', type: 'get', success: function(data) { $.each(data.items, function(item) { console.log(item); }); }, error: function(e) { console.log(e.message); } }); }); 

I get a jQuery error (line 16, a not defined). What am I doing wrong?

+8
javascript jquery ajax
source share
2 answers

Assuming your JSON is like this

 var item= { "items": [ { "FirstName":"John" , "LastName":"Doe" }, { "FirstName":"Anna" , "LastName":"Smith" }, { "FirstName":"Peter" , "LastName":"Jones" } ] } 

You can request it like this:

 $.each(item.items, function(index,item) { alert(item.FirstName+" "+item.LastName) }); 

Example: http://jsfiddle.net/4HxSr/9/

EDIT: According to JSON OP Added later

There are no elements in your JSON , so it is not valid.

Like your json like this

 var item= { "COLUMNS": [ "username", "password" ], "DATA": [ [ "foo", "bar" ] ,[ "foo2", "bar2" ]] } 

You should request it like this:

 console.debug(item.COLUMNS[0]) console.debug(item.COLUMNS[1]) $.each(item.DATA, function(index,item) { console.debug(item[0]) console.debug(item[1]) }); 

Working example: http://jsfiddle.net/4HxSr/19/

+11
source share

You need to add:

 dataType: 'json', 

.. so you should have:

 $("#button").click(function(){ $.ajax({ url: 'http://localhost/test.php', type: 'get', dataType: 'json', success: function(data) { $.each(data.COLUMNS, function(item) { console.log(item); }); }, error: function(e) { console.log(e.message); } }); }); 

.. and also ensure that you indicate COLUMNS in each statement.

getJson is another way to do this.

http://api.jquery.com/jQuery.getJSON/

+3
source share

All Articles