I'm trying to delete a row from a Datatable that uses server side processing (removing the row data and the row/tr visually) based on the value of certain attribute of the row.
I'm using the remove()
function to do it and it removes the row data, but visually the table stills the same.
So I added the draw()
function but it reinitializes the table, including the data.
So, how can I "redraw" the table after removing a row from the Datatable that uses server side processing? Is there any other function like draw()
to redraw the table but using only the existing data in the datatable?
$("#tableSelector").DataTable()
.rows( function ( idx, data, node ) {
return data.attribute_value == value_to_delete;
} )
.remove()
.draw();
Finally, I found the solution.
I followed this thread then read about the DataTable's property "dataSrc".
Then with this information searched for something similar in Stack Overflow and found this.
So the trick to do what I asked for was to use a variable to filter the row which I want to ignore in the ajax call.
I've reused the code provided in the referred question. And this is the result:
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Status</th>
<th>Message</th>
<th>Details</th>
</tr>
</thead>
</table>
JS:
$(document).ready(function() {
function loadDataTable(excluded_name = undefined){
$("#example").DataTable().destroy();
$('#example').DataTable({
// "processing" : true,
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
"dataSrc": (json) => {
if(excluded_name !== undefined){
return json.filter((item) => item.name !== excluded_name)
}else{
return json
}
}
},
"columns" : [ {
"data" : "name"
}, {
"data" : "email"
}, {
"data" : "subject"
}, {
"data" : "status"
},{
"data" : "message"
},
{
"mData": "Details",
"mRender": function (data, type, row) {
return "<a class='delete' data-name='"+ row.name + "' data-id=" + row.id + " href='/Details/" + row.id + "'>Delete</a>";
}
}]
});
}
$(document).on("click", ".delete", function(e) {
e.preventDefault()
let excluded_name = $(this).data("name")
alert("Excluding this name in the next load: " + excluded_name);
loadDataTable(excluded_name);
})
loadDataTable();
});
Fiddle: https://jsfiddle.net/ek94mh1x/4/
Note: This is a client side "delete", I know this could be done with server side processing, but in my case I was only allowed to do it in the client side.
Additionally, in case you need to delete multiple rows you could use an array as a parameter and follow the same logic.
I hope this could help someone.