sabsab sabsab - 5 months ago 10
jQuery Question

jQuery Parsing JSON array to a table

I was having this

JSON
structure

[
{
"id":"3",
"0":"3",
"name":"What ever",
"1":"What ever",
"email":"dd@dd.dd",
"2":"dd@dd.dd",
"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":"sabsab58@gmail.com",
"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?

Answer

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