panjo
panjo

Reputation: 3515

populate jquery data table with returned json data

I have some json objects which are returned based on user input

$('#button').click(function () {
        var usersData= $('input[name="UserInputData"]').val();

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ UserInputData: usersData}),
            url: '/Home/Data',
            success: function (result) {
                $.each(result, function (i, item) {
                    // how to invoke data table and populate with returned
                    // item object, for ex. item.Title                    
                });
            },
            error: function () { alert("error"); }
        });
    });

Just to clarify I'm getting list of json object from controller, that's ok, I'm struggle with how to display these data on data table.

Upvotes: 0

Views: 5872

Answers (1)

Andrei
Andrei

Reputation: 56726

success: function (result) {
    //if table is already on the page
    var table = $("table-selector");
    table.find("tr").remove(); //remove all previous rows if needed

    //or, if table does not exist
    var table = $("<table></table>");
    $("table-container-selector").append(table);

    $.each(result, function (i, item) {
        var tr = $("<tr></tr>");
        table.append(tr);

        var td = $("<td>" + item.field1 + "</td>");
        tr.append(td);

        var td = $("<td>" + item.field2 + "</td>");
        tr.append(td);

        var td = $("<td>" + item.field3 + "</td>");
        tr.append(td);
    });
},

Upvotes: 3

Related Questions