Reputation: 1311
I was having this JSON
structure
[
{
"id":"3",
"0":"3",
"name":"What ever",
"1":"What ever",
"email":"[email protected]",
"2":"[email protected]",
"mobile":"7777777",
"3":"7777777",
"address":"Bikrom Pur",
"4":"Bikrom Pur"
}
]
Everything was working just fine when I parse these data though a table using the following jQuery function:
function renderUserList(jsonData) {
var table = '<table width="600" cellpadding="5" class="table table-hover table-bordered"><thead><tr><th scope="col">Name</th><th scope="col">Email</th><th scope="col">Mobile</th><th scope="col">Address</th><th scope="col"></th></tr></thead><tbody>';
$.each( jsonData, function( index, posts){
table += '<tr>';
table += '<td class="edit" field="name" user_id="'+posts.id+'">'+posts.name+'</td>';
table += '<td class="edit" field="email" user_id="'+posts.id+'">'+posts.email+'</td>';
table += '<td class="edit" field="mobile" user_id="'+posts.id+'">'+posts.mobile+'</td>';
table += '<td class="edit" field="address" user_id="'+posts.id+'">'+posts.address+'</td>';
table += '<td><a href="javascript:void(0);" user_id="'+posts.id+'" class="delete_confirm btn btn-danger"><i class="icon-remove icon-white"></i></a></td>';
table += '</tr>';
});
table += '</tbody></table>';
$('div#content').html(table);
}
I updated my server-side script to generate this JSON structure
{
"success":1,
"message":"Post Available!",
"posts":[
{
"id":"39",
"name":"Ahmed",
"email":"[email protected]",
"mobile":"778899",
"address":"41122333"
}
]
}
After I updated the JSON structure I could not parse the data through the table again, all what I get on the table's fields is undefined
. I am a quiet beginner on JSON and jQuery.
What should I change on the jQuery function to make the app works as before and how can I get to inner JSON array on my jQuery?
Upvotes: 0
Views: 396
Reputation: 467
change $.each( jsonData, ...
to
$.each( jsonData.posts, ...
Because you are traversing jsonData.posts
Upvotes: 1
Reputation: 661
Try to loop over
jsonData.posts
Like:
$.each( jsonData.posts, function( index, posts){
table += '<tr>';
table += '<td class="edit" field="name" user_id="'+posts.id+'">'+posts.name+'</td>';
table += '<td class="edit" field="email" user_id="'+posts.id+'">'+posts.email+'</td>';
table += '<td class="edit" field="mobile" user_id="'+posts.id+'">'+posts.mobile+'</td>';
table += '<td class="edit" field="address" user_id="'+posts.id+'">'+posts.address+'</td>';
table += '<td><a href="javascript:void(0);" user_id="'+posts.id+'" class="delete_confirm btn btn-danger"><i class="icon-remove icon-white"></i></a></td>';
table += '</tr>';
});
Upvotes: 1