user2281858 user2281858 - 2 months ago 36
Ajax Question

Child rows in DataTables using AJAX

I am trying to bind a child table with a parent table. I am not able to figure out how this can be done when the data for the child table is coming through an AJAX call which then creates a dynamic table.

I have followed this

Below is my code.

$('#myTable tbody).on('click', 'td.details-control', function () {

var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);

if (row.child.isShown()) {
// This row is already open - close it

row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row

row.child(format()).show();
tr.addClass('shown');
}
});

function format() {

$.ajax({
type: 'GET',
url: '@Url.Action("MyFunction", "Home")',
data: { "Id": MyId },
dataType: "json",
async: false,
success: function (data) {
var list = data;
$.each(list, function (index, item) {

return '<table>.......<table />';

//i need to loop across the list and create a dynamic table with tr and td


});
},
error: function (result) {
var error = JSON.stringify(result);
throw "Error...";
}
});
}

Answer
$('#myTable tbody).on('click', 'td.details-control', function () {

    var tr = $(this).closest('tr');
    var row = $('#myTable').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it

        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        format(row.child);  // create new if not exist
        tr.addClass('shown');
    }
});

and then the format() will be

function format(callback) {
    $.ajax({
        .... 
        //async: false, you can use async 
        success: function (data) {
            var list = data;
            var html = '';
            $.each(list, function (index, item) {
                ...
                //create <tr> <td> with loop
                html= '<tr><td>.......</tr>';
            });
            callback($('<table>' + html + '</table>')).show();
        },
        ...
    });
}

demo here jsfiddle

Comments