I’m using DataTables in Laravel, and I want to delete a row from the database. It used to work when I did it as a get request in the route, but since I changed it to the delete request and put the csrf and method under the form, it stopped working. I receive – Data Not Deleted
error. What can be a reason of that happening? Button that I receive from the index controller:
$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">
@csrf
@method('DELETE')
<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::delete('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);
Controller function:
public function destroy($id)
{
$data = Employee::findOrFail($id);
$data->delete();
}
2
Answers
To solve the problem I had to put csrf inside the meta:
And use this at the beginning of the script:
In your route you are using delete method, but in ajax call you have not mentioned the method, so the error is 405 method not allowed,
Try adding
type: delete
in ajax. something like this: