Django Ajax Datatable Loses Sort and Pagination
Django Ajax Datatable Loses Sort and Pagination
thedarkring
Posts: 8Questions: 1Answers: 0
I am updating my datatable like this:
var mytable = $("#my-table").dataTable({
stateSave: true
});
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#my-table tbody").html(data.html_mytable);
$("#modal-my").modal("hide");
}
else {
$("#modal-my .modal-content").html(data.html_form);
}
}
});
return false;
};
The problem is that after the saveForm function executes. The page displays all the rows of the datatable, it also loses the sort settings. If I click the sort column or filter, the datatable will look correctly again. I realize the I am appending html to the table and datatable doesn't understand. What is the easiest workaround for this?
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
The best option is to use Datatables API's to add the data. You can use
clear()
to clear the table, if desired then userows.add()
to add the rows to the table.However if that is not an easy option then you can use something like
rows().invalidate()
to have Datatables update its cache.Kevin
Any chance you can show me what the easier option would look like in my code above?
Try this:
Kevin
The results are the same. The table still reflects the changes. But it loses its previous sort and it also displays all the rows.
This works to display the page I was on, but the data is not updated.
I tried this with the same result.
Sorry I forgot to include
draw()
to redraw the table. If you want the table to stay on the same page you can use `.draw(false):Kevin
Please see my above comment.
The data is not reflecting as updated when I do a draw. With or without the 'dom'. I should also note that I am using client side processing, not server side.
I tried it in the below example and realized that when you replace the
tbody
html you are also removing anything Datatables may have added. In my example I usedestroy()
before adding the html the reinitialize a new Datatable.http://live.datatables.net/tehuzeto/1/edit
Click the button
Update Data
to see it in action.Kevin
OMG thank you! I am 99% the way there. It still loses the page you were on and the sort settings. But it's no longer displaying all the rows.
You are really the best!!!!!!!! Thanks for your help. I have it working now and here is the final code: