reload dynamic table
reload dynamic table
a while back I had found code to be able to load a table using a dynamic data source.
$.ajax({
url: "api/CallManagerUnmatched",
success: function (data) {
var columns = [];
if (data.length !== 0) {
//build the DataTable dynamically.
columnNames = Object.keys(data.Table[0]); //.Table[0]] refers to the propery name of the returned json
for (var i in columnNames) {
columns.push({
data: columnNames[i],
title: columnNames[i]
});
}
}
$('#CallManagerUnmatched').DataTable({
dom: 'frtip',
data: data.Table,
rowId: 'CM_ID',
scrollX: true,
columns: columns
})
}
});
It works perfectly because I am able to change the dataset without having to change the javascript, especially while this project is still in development phase. However, I am now needing to do a ajax.reload() and can't figure out the syntax. myDataTableName = $('#CallManagerUnmatched ... but that didn't seem to work when I tried myDataTableName.ajax.reload(); The error I get on reload is: datatables.min.js:77 Uncaught TypeError: Cannot set property 'data' of null
This question has an accepted answers - jump to answer
Answers
when I try putting the variable name at the first line:
CallManagerUnmatchedDataTable = $.ajax({
I get:
Uncaught TypeError: Cannot read property 'reload' of undefined
To issue an
ajax.reload()
, the table must've been loaded byajax
to begin with. This isn't the case for you though, as you've got the Ajax call external to DataTables, and you're just passing in the returned data todata
.You would need to rejig your code to either use
ajax
, or have a function that calls the ajax call externally again.Colin
I moved it out into a function and call it instead of a reload, but I get an error that I cannot reinitialise. So, if I need to destroy, I am back to the issue of not having a variable name assigned to it. I am lost...
If you don't want to destroy the table then one option is to use the
$.fn.dataTable.isDataTable()
API to determine if the table is a Datatable. If is not then initialize like you have. If it is then useclear()
to remove the current rows (if desired) followed byrows.add()
.I don't see where you are assigning a variable name. Is it for the Datatabe's API access? You can use the steps in the API docs to get the API instance.
Kevin
actually, I just ran across the isDataTable as well as the destroy option. I chose the latter and it appears to work!