Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload dataTable after deleting records/data?

I have generated records and each row has delete button, And when I click delete button it will delete the records from the db. Also, after delete it will reload dataTable. Any Help for this?

DataTables:

var table = $('#table').DataTable({

    "processing": true,

     //some settings?
});

jQuery:

$(document).on('click', '[id^="delete-product-"]', function() {

    var id = this.id.split('-').pop();

    $.ajax({
        type: 'post',
        url: 'my_controller/delete_product',
        dataType: 'json',
        data: {id: id},
        success: function(callback)
        {
            //What should I code here, that can't reload entire page, only the table 
            //after deleting records
        },
        error: function(status)
        {
            console.log(status);
        }
    });
});

Any help would be appreciated. Thank you in Advance

like image 280
Marky Onyab Avatar asked Nov 16 '16 08:11

Marky Onyab


People also ask

What does DataTable destroy do?

function destroy( [ remove ] )Restore the tables in the current context to its original state in the DOM by removing all of DataTables enhancements, alterations to the DOM structure of the table and event listeners.


1 Answers

You don't have to reload whole table data, just remove the deleted row.

$(document).on('click', '[id^="delete-product-"]', function() {
    var $button = $(this);
    var id = this.id.split('-').pop();
    var table = $('#table_id_selector').DataTable(); // replace with your table id 
    selector
    $.ajax({
        type: 'post',
        url: 'my_controller/delete_product',
        dataType: 'json',
        data: {id: id},
        success: function(callback)
        {
            table.row( $button.parents('tr') ).remove().draw();
        },
        error: function(status)
        {
            console.log(status);
        }
    });
});
like image 152
Ergec Avatar answered Oct 11 '22 23:10

Ergec