Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through JSON within a $.ajax success

When a user clicks a button I want to return some data and iterate through the JSON so that I can append the results to a table row.

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

My JSON is coming back 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'm getting a jQuery (line 16, a is not defined) error. What am I doing wrong?

like image 561
Jason Wells Avatar asked Jun 12 '12 03:06

Jason Wells


2 Answers

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);
    }
});

});

.. as well as ensuring that you are referencing COLUMNS in the each statement.

getJson is also another way of doing it..

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

like image 112
Sp4cecat Avatar answered Sep 20 '22 18:09

Sp4cecat


Assuming your JSON is like this

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

You can query it like this

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

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

EDIT : As per the JSON OP Posted later

Your JSON does not have an items, so it is invalid.

As per your JSON like this

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

You should query 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 sample : http://jsfiddle.net/4HxSr/19/

like image 44
Shyju Avatar answered Sep 22 '22 18:09

Shyju