The main reason for destroying a dataTables instance is if you want to change the initialisation options - like change paging
and so on. Or if the table structure should be altered. None of those circumstances seems to be the case here? To answer the question, the safest way to destroy and reinitialise a table is to use the shorthand option destroy: true
:
var table = $('#records_table').DataTable({
...
destroy : true
});
To go further, I think you are doing it a little backwards.
- Why empty the table with jQuery
$('#records_table tbody').empty();
instead of table.clear()
?
- Why inject records with jQuery
$('#records_table tbody').append(trHTML);
instead of using table.row.add([...])
?
Here is a code scenario similar to the one in the question, which reinitialises the dataTable without conflicts, each time the modal is shown :
var table;
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table, if it exists
if (table) table.clear();
//reinitialise the dataTable
table = $('#records_table').DataTable({
destroy: true,
bLengthChange: false,
paging: false
});
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
see demo -> http://jsfiddle.net/bz958dxj/
But you really dont need to destroy the table at all, it just slows down performance :
//global table object
table = $('#records_table').DataTable({
bLengthChange: false,
paging: false
});
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table
table.clear();
//insert data
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
demo -> http://jsfiddle.net/8mjke9ua/
NB: I just assume
we are talking about bootstrap modals, based on the reference to .modal-header
in the question.
NB2: Notice the $.parseJSON(response.contents)
, you should do it as you are doing it in the question. The only reason for this is that the examples go trough a proxy to avoid the same-origin policy.