DataTable not adhearing to destroy attribute
DataTable not adhearing to destroy attribute
I have a kind of complicated situation where I have to dynamically define the columns array prior to defining the DataTable.
I do this via an ajax call that returns both the data I need for the columns and the row data for the DataTable. The column number always matches the number of fields in the row data.
In the 'success' function of that ajax call, I do all the work of building the columns array, create the data set for the DataTable and define the DataTable itself utilizing those variables. It works perfectly the first time, but when I reload with a different data set, it fails. I do have destroy set to true.
If there are more columns in the second load I get the error: TypeError: m[n] is undefined
If there are less columns in the second load, I get the error: TypeError: c is undefined
I wish I could put up a working example, but it is really a lot of code. If you need one, I'll do my best to put one somewhere.
Basically, it looks like this:
jQuery.ajax({
url: '/index.php',
type: 'POST',
dataType: 'json',
data: {
action: 'search'
},
success: function(results) {
var data = results['data'],
columnData= results['columnData'],
columns = [];
jQuery.each(columnData,function(k,v) {
columns.push({data: k,title: v,render: {display: 'display',export: 'export',sort: 'export',filter: 'text'}});
});
DT = jQuery('#theTable').DataTable({
destroy: true,
scrollY: (jQuery(window).height()-(jQuery('#navMenu').height()+jQuery('#contentContainer').height()+jQuery('.footerBar').height()+120)),
scrollCollapse: true,
deferRender: true,
paging: false,
scroller: false,
data: data,
columns: columns
});
}
});
It is almost like the DataTable is not getting destroyed so that it can be redefined with the new columns and row data.
I'm using DataTables 1.10.18 with Bootstrap 4 styling.
Thanks for your help,
Steve
Replies
As a pretty horrible workaround, this seems to do the trick.
Since DT is defined globally, prior to calling the above ajax the second time:
I'd still like to hear from you guys to see if there is a more elegant way of accomplishing this.
As always, thank you,
Steve
The problem seems to be that the original table, including the thead, still resides in HTML when being destroyed. This seems to cause problems when changing the number of columns. I'd recommend using
destroy()
followed by using jQuery empty() to empty the HTML contents before re-initializing the new Datatable. Here is an example you can experiment with:http://live.datatables.net/pelupixa/1/edit
You can input the number of columns to re-init with.
Kevin