Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic html table with complex JSON

Tags:

jquery

ajax

I have an aspx page, which is calling a ajax method to return a JSON object containing arrays of Countries.

I want to loop through the data and create

  • COUNTRY
within a table for each entry.

From what I can see, my code looks good, but i'm not getting any results written to my div.

I've set up a Fiddle with data and would appreciate some assistance.

http://jsfiddle.net/L3s6c0yx/1/

and here is the JS code

var tdata = "{"d": "[{\"Countries\":[\"Cyprus: 3\",\"Panama: 3\"]},{\"Countries\":[\"Malaysia:     1\",\"Malaysia: 2\"]},{\"Countries\":[\"Tanzania: 3\"]}]"}";

$.ajax({
type: "POST",
url: "",
data: tdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
    tdata = jQuery.parseJSON(result.d);

    var response = '',
        indicator = '';
    for (var i = 0; i < tdata.length; i++) {
        response += '<div class="item">' +

            '<table style="height: 300px;">' +
            '<tbody>' +
            '<tr>' +
            '<td><label>Countries</label></td>' +
            '<td><ul>' + $.each(tdata[i]['Countries'], function (value) {
            response += '<li>' + value + '</li>';
        });
        response += '</ul></td></tr>' +
            '</div>';
    }
    $('#countries').append(response);
 }
});

Image showing the UL

like image 891
CSharpNewBee Avatar asked Apr 15 '26 08:04

CSharpNewBee


1 Answers

get this inside your for loop:

for (var i = 0; i < tdata.length; i++) {
    response += '<div class="item">' +

    '<table  class="table table-user-information" style="height: 300px;">' +
    '<tbody>' +
    '<tr>' +
    '<td><label>Countries</label></td>' +
    '<td><ul>';

    $.each(tdata[i]['Countries'], function (index, value) {
        response += '<li>' + value + '</li>';
    });

    response += '</ul></td></tr>' + '</div>';
}

http://jsfiddle.net/L3s6c0yx/6/

You were adding $.each function to your string which returns arrays. Hope this is what you were looking for.

like image 191
Zanuff Avatar answered Apr 19 '26 09:04

Zanuff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!