Undermine2k Undermine2k - 10 days ago 6
Javascript Question

datatables ajax reload from new source

How do I reload datatables with the new ajax functionality?

I think it's a problem of scope.

function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
'sAjaxSource' : src,

'fnServerData' : function(sSource, aoData, fnCallback)
{
$.ajax({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
});
}


Try to reload it from a different data source:

$("input[type="button"]").on('click',function()
{

oTable.ajax.url( 'newsource' ).load();
alert( 'Data source: '+oTable.ajax.url() );


});


Alert outputs : src : newsource

Browser loads table from src: oldsource

Answer

I've had the same issue to anyone who runs into this problem in the future here is the solution:

To accomplish reloading of data from a different source:

refer to the DOM table element NOT the DataTable object or you will get a reinitilization error:

step 1: clear data :

$('#your_table_name').DataTable().clear();

step 2: Destroy the DataTable object

 $('#your_table_name').DataTable().destroy();

if you're using child rows this is very important remove the click listener

   $( "#your_table_name tbody" )
    .off( "click", "td.details-control");

Reinit DataTables:

loadTable('newsource','your_table_name')

and your loadTable function

function loadTable(src,tableName)
{
var oTable = $('#'+tableName).DataTable({
  'bProcessing'    : true,
  'bServerSide'    : true,
        'responsive' : true,
         "sDom": '<"toolbar"lfr>tip<"F">R',

  'sAjaxSource'    : src,

   });

  //initchildrows()
}