enigmaticus
enigmaticus

Reputation: 548

Accessing JSON through javascript

I am a newbie with json and right now fighting with it. :) I am getting response with ajax call and I want to get all id values from json response. I am not sure what am I doing wrong, I already tried most of the solutions but none gave me a positive answer.

This is my code:

$.ajax({
    url: 'Actions.php?action=update',
    type: 'post',
    data: '&id='+$id,
}).success(function(data) {
    var jsondata = JSON.parse(data);

    $.each(jsondata, function(i, item) {
       console.log(item.Records.id);
    });           
});

And error I am getting is this one:

TypeError: item.Records is undefined

And this is my JSON response:

{"Result":"OK","Records":
[{"0":"111","id":"111","1":"20","free":"20"},
{"0":"127","id":"127","1":"20","free":"20"},
{"0":"133","id":"133","1":"20","free":"20"},
{"0":"134","id":"134","1":"20","free":"20"},
{"0":"135","id":"135","1":"20","free":"20"},
{"0":"326","id":"326","1":"20","free":"20"}]}

How can I acces all id and free values? Or what am I doing wrong?

Upvotes: 0

Views: 62

Answers (3)

Maneesh Singh
Maneesh Singh

Reputation: 575

$.ajax({
url: 'Actions.php?action=update',
type: 'post',
data: '&id='+$id,
dataType:'json'
 }).success(function(data) {

$.each(data.Record, function(i, item) {
   console.log(item.id);
});           

});

pls use dataTye in your ajax setting.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to iterate over jsondata.Records:

$.each(jsondata.Records, function (i, item) {
    console.log(item.id);
});

Example fiddle

Upvotes: 3

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

jsondata.Records is the array which contains further json objects,

Try,

$.each(jsondata.Records, function(i, item) {
   console.log(item.id);
}); 

Upvotes: 2

Related Questions