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
Advertisement
Answer
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) { ...... });