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?
When you add/delete a record, you'll want to redraw the table. This should refresh the table with the new information for you. $('#myTableID'). DataTable().
There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library. It is a highly flexible tool that is basically created to display information in tables as well as adding interactions to them, hence, enhancing data accessibility in HTML tables.
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
}
});
I was able to solve this issue with much simple approach than provided in above answers.
Ajax call to delete data from backend
First of all delete the data from backend using normal ajax async call.
Delete from frontend datatable
Get the row TR which you want to delete and use the datatable function fnDeleteRow
to delete this row. This will automatically refresh the table so you will not need any fnDraw
or other stuff.
//in my case its delete button which was clicked
//so I got its parents parent which is TR row
var row = $(this).parent().parent();
$('DATA TABLE SELECTOR').dataTable().fnDeleteRow(row);
And you are done.. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With