How to reinitialize dataTables with newly fetched data from server using ajax in MVC
The error message http://datatables.net/tn/3 states the problem precisely. You're re-initializing the table with different options in fetchNews()
.
You need to destroy the table first, see http://datatables.net/manual/tech-notes/3#destroy. You can do that with $("#dailyNews").dataTable().fnDestroy()
(DataTables 1.9.x) or $("#dailyNews").DataTable().destroy()
(DataTables 1.10.x).
function fetchNews(context){ if(context!="") { // Destroy the table // Use $("#dailyNews").DataTable().destroy() for DataTables 1.10.x $("#dailyNews").dataTable().fnDestroy() $("#dailyNews").dataTable({ // ... skipped ... }); }}
Alternatively, if you're using DataTables 1.10.x, you can initialize the new table with additional option "destroy": true
, see below.
function fetchNews(context){ if(context!="") { $("#dailyNews").dataTable({ "destroy": true, // ... skipped ... }); }}
This worked for me after a lot of research:- First check if dataTable exist or not,if does destroy the dataTable and then recreate it
if ($.fn.DataTable.isDataTable("#mytable")) { $('#mytable').DataTable().clear().destroy();}$("#mytable").dataTable({... });
Datatables has a retrieve option. If your table receive other content after inicialization you can set the parameter: retrieve: true,
You can watch the documentation here: https://datatables.net/reference/option/retrieve
$("#body_data").load("/Admin/GetDailyNews", function () { $("#dailyNews").dataTable({ retrieve: true, "lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]], "columnDefs": [{ "targets": 3, "orderable": false }], "pagingType": "full_numbers", "oLanguage": { "sSearch": "" }, "deferRender": true });
}