InfoLearner InfoLearner - 5 months ago 811
jQuery Question

How to refresh jquery datatable after deleting a row

Each row in the data table has a delete button.

On click of the delete button, I am calling this code:

$('.deleteButton').live('click', function () {

var $this = $(this);
var url = $this.attr("id");
$("#example").fnReloadAjax();
$.getJSON(url, Success());
});


The url is action of the controller that takes the Id and deletes the data from the database. That works.
I now want to call the refresh/redraw function of datatable so it can load new results but it doesn't work.

Datatable is:

$("#example").dataTable({
"aoColumns": [
{ "sTitle": "Id" },
{ "sTitle": "Name" }],


"bProcessing": true,
"bServerSide": true,

"sAjaxSource": '@Url.Action("FetchData", "Home")',
"sPaginationType": "full_numbers",

});


Can anyone please advice?

Answer

Quoted from the API datatable page - on the fnReloadAjax() bullet:

Note: To reload data when using server-side processing, just use the built-in API function fnDraw rather than this plug-in.

Thus, you'd probably better use fnDraw.

[EDIT] Actually, the order of your calls should be:

// you don't have to use $.json because you don't use the downloaded data
// first, ask the server to delete the data   
$.ajax({
   url: urlToDelete,
   success: function() {
       // if it worked, ask datatable to redraw the table with the new data
       $("#example").dataTable().fnDraw();
       // if this js function does anything useful (like deleting the row), then call it:
       Success();
   },
   error: function() {
       // display any error (like server couldn't be reached...), or at least try to log it
   }
});
Comments