I’m using DataTables in Laravel, and my goal is to delete a row from database and then reload the list of data. But for some reason it does not work. I receive – Data Not Deleted
error, and also setTimeOut
function seems to not work, because a message does not disappear. I’m a newcomer to Ajax so it’s hard for me to find the reason of what is wrong. Button:
$button = ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="fas fa-fw fa-trash"></i> Delete</button>';
HTML form that appears when a delete button is clicked:
<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="sample_form" class="form-horizontal">
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Confirmation</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
</div>
</form>
</div>
</div>
</div>
Script:
var employee_id;
$(document).on('click', '.delete', function(){
employee_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function(){
$.ajax({
url:"/admin/employees/destroy/"+employee_id,
beforeSend:function(){
$('#ok_button').text('Deleting...');
},
success:function(data)
{
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Deleted');
}, 2000);
},
error: function(xhr, status, error) {
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Not Deleted');
}, 2000);
},
})
});
});
Route:
Route::get('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);
Controller function:
public function destroy($id)
{
$data = Employee::findOrFail($id);
$data->delete();
}
2
Answers
In ‘form’ you have method POST, but in Route, you have it as Get.
I would try put following under tag:
Or perhaps add following to ajax call, instead of @csrf and @method:
Then ammend Route from Get to Delete:
change your
<form>
method="post"
tomethod="get"
also you forgot use
@csrf
token indside fromalso change the query in controller
for set time out you can use this like