Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleted DataTable row gets added again after sorting

I am using the DataTables jQuery plugin to display an HTML table and I have made an AJAX row deletion function that sends the deletion POST request in the background and displays the returned HTML message in an #info div and removes the related HTML row from the DOM using the jQuery remove() function.

Here's the function that gets called as deleteData($id) from the row's delete button:

function deleteData(id)
{
    var data = "id="+id;

    $.ajax(
        {
            type: "POST",
            url: "delete.php",
            data: data
        }
    ).done
    (
        function(data)
        {
            $('#info').html(data);

            var setID = id;

            $('#row' + setID).remove();         
        }
    );
}

Everything works good so far, the row gets deleted and the return message is shown, however, when I click a header to sort the rows again (ascendingly or descendingly) the deleted row reappears (in current session, not after a page reload) and it's still searchable, I wish to fix that.

From what I've read, the issue is that DataTables only loads the table once, but there's some way to make it load from the DOM at each sort. I have tried many different ways to do that but it doesn't work.

like image 695
Achraf Almouloudi Avatar asked Dec 05 '22 01:12

Achraf Almouloudi


1 Answers

I never used DataTable before but reading your question I was curious to learn a bit.

Then I noticed that you're removing the row merely using jQuery .remove() on the given row (in other words removing the real exposed DOM row), while this DataTable page states you should use the dedicated .row().remove().

So in your example I guess you should replace $('#row' + setID).remove(); by yourDataTable.row($('#row' + setID)).remove();.

EDIT.
Thanks to the @Bryan Ramsey's comment, I just realized that my suggested solution was incomplete:

  • the statement used by the OP $('#row' + setID).remove(); only removes the row from DOM, but keeps it in the DataTable object so it appears again furtherly
  • then I suggested to rather use yourDataTable.row($('#row' + setID)).remove();, which really removes the row from the DataTable object, but now keeps it in the DOM so it doesn't visually disappear before the next change happens!
  • so the real complete solution is yourDataTable.row($('#row' + setID)).remove().draw();, where draw() ensures the row to immediately disappear.

NOTE: (if you're getting .row is not a function or $datatable is not defined) You must reintialize your datatable before removing the row as

var $datatable = $('#datatable-selector').DataTable();
$datatable.row($deletingRowSelector).remove().draw();
like image 168
cFreed Avatar answered Dec 09 '22 15:12

cFreed