nagazi nagazi - 4 months ago 22
Ajax Question

DataTable Sortable with dynamic data source

I have a table with events between 'Time1' and 'Time2'.

On click on 'Load' the data will be loaded by a ajax function, with some parameter.

Now I want to use a sortable table...DataTable

The Table initialize correct. But if I add the rows with

$('table').append('<tr><td> ' + row.id + '</td><td>' + row.name + '</td></tr>');


I can not sort the table.

How I can realize it with Ajax to make the table sortable? I dont know how the DataTable Manual means it

<table class="table table-bordered" id="report-table" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody id="report">
</tbody>
</table>


And the Javascript:

$(document).ready(function() {
var dataset = null;

$('#report-table').dataTable({
data: dataset,
columns: [
{ title: 'ID' },
{ title: 'Name' }
]
});

$('#btn-load, .btn-filter-apply').on('click', function() {
$('#filter').modal('hide');

var data = new Array();
$('.filter-list tr').each(function(idx, row) {
data.push([$(row).find('td').eq(0).text(), $(row).find('td').eq(1).text(), $(row).find('td').eq(2).text()]);
});

$.post('/data', { from: $('#ipDateTimeFrom').val(), till: $('#ipDateTimeTo').val(), data: data, ip: $('#sb-server option:selected').val() }, function(resp) {
$('#report').html('');
dataset = resp.data;
$.each(resp.data, function(idx, row) {
$('#report').append('<tr style="background-color:#ffffff"><td>' + row.ID + '</td><td>' + row.Name + '</td></tr>');
});
});
});
});

Answer

See dataTable.row.add() and dataTable.order() - you shouldn't need AJAX to reorder the dataTable. EDIT Please note this requires you follow the proper dataTable convention of adding data tow the table using the dataTable.row.add() method, hence including that in the code:

$(document).ready(function() {
  var dataset = null;

  // Table represented as var table.
  var table = $('#report-table').DataTable({
    data: dataset,
    columns: [{
      title: 'ID'
    }, {
      title: 'Name'
    }]
  });

  var rowData = [ "id", "title" ];

  // Add an array of row data, e.g., [ "id", "title" ], have to redraw
  // when we modify table.
  table.row.add(rowData).draw(false);

  $('#btn-load, .btn-filter-apply').on('click', function() {
    $('#filter').modal('hide');

    var data = new Array();
    $('.filter-list tr').each(function(idx, row) {
      data.push([$(row).find('td').eq(0).text(), $(row).find('td').eq(1).text(), $(row).find('td').eq(2).text()]);
    });

    // Order based on index - maybe you can use your mysterious
    # $("filter-list tr") query above to order more dynamically
    table.order([1, 'asc'], [2, 'asc']).draw();
  });
});

Also note that you can source data from an AJAX source in the initializer as follows, if you wish:

$('#report-table').dataTable( {
  "ajax": "data.json"
});

EDIT: JSFiddle.