Laravel yajra/Datatables action delete is not work

2019-06-03 13:15发布

问题:

hy, i'm now using L5 and yajra/datatables plugin, everything work fine until i create delete button to delete record, the delete button is not working
here is my controller :

public function data() 
{
    $news = DB::table('news')
        ->join('users', 'news.user_id', '=', 'users.id')
        ->select(['news.id', 'news.judul', 'news.gambar', 'users.name']);

    return Datatables::of($news)
        ->addColumn('action', function ($id) {
            return '<a href="news/' . $id->id . '/edit" class="btn btn-primary">Edit</a>
            <button class="btn-delete" data-remote="/news/' . $id->id . '">Delete</button>'; 
        })->make(true);
}

Here is my JS :

var table = $('#news-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('news.data') !!}',
        columns: [
            {
                "className": 'details-control',
                "orderable": false,
                "data": null,
                "defaultContent": ''
            },
            {data: 'id', name: 'news.id'},
            {data: 'judul', name: 'news.judul'},
            {data: 'name', name: 'users.name'},
            {data: 'action', name: 'action', orderable: false, searchable: false}
        ],
        order: [[1, 'asc']]
    });

//problem starts here
$('#news-table').DataTable().$('.btn-delete[data-remote]').on('click', function (e) { 
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var url = $(this).data('remote');
    // confirm then
    $.ajax({
        url: url,
        type: 'DELETE',
        dataType: 'json',
        data: {method: '_DELETE', submit: true}
    }).always(function (data) {
        $('#news-table').DataTable().draw(false);
    });
});

the JS event for btn-delete[data-remote] is not working, it's no return error in console, but nothing happen when i click it

回答1:

Its maybe not working because one the moment you binding your click event on the table there isn't any elements in it. And so its not possible to bind the click event on an element named .btn-delete[data-remote].

Maybe it works if you bind the click event on the table and let it trigger if clicked on .btn-delete[data-remote], like:

$('#news-table').on('click', '.btn-delete[data-remote]', function (e) { 
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var url = $(this).data('remote');
    // confirm then
    $.ajax({
        url: url,
        type: 'DELETE',
        dataType: 'json',
        data: {method: '_DELETE', submit: true}
    }).always(function (data) {
        $('#news-table').DataTable().draw(false);
    });
});

// or maybe this
$('#news-table').DataTable().on('click', '.btn-delete[data-remote]', function (e) { 
    ...... 
});


回答2:

I think you bind dynamic data with your table so it will not effect directly on click. So you may use $('body') or $(document) to trigger click event. Also you might need to comment/remove e.preventDefault(); . This also stop further process.

So updated code will be like :

//problem starts here
$('body').on('click', $('#news-table').DataTable().$('.btn-delete[data-remote]'),  function (e) { 
    //e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var url = $(this).data('remote');
    // confirm then
    $.ajax({
        url: url,
        type: 'DELETE',
        dataType: 'json',
        data: {method: '_DELETE', submit: true}
    }).always(function (data) {
        $('#news-table').DataTable().draw(false);
    });
});


回答3:

This is because delete button cannot binding before the datatables being constructed.

solution is need to wait after datatables DOM events

official solution from https://datatables.net/reference/event/

$('#myTable').on('draw.dt', function () {
    alert('Table redrawn');
    // do the button binding work..
});