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.'" > <i ></i> Delete</button>';
HTML form that appears when a delete button is clicked:
<div id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div >
<div >
<form method="post" id="sample_form" >
@csrf
@method('DELETE')
<div >
<h5 id="ModalLabel">Confirmation</h5>
<button type="button" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div >
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div >
<button type="button" data-bs-dismiss="modal">Close</button>
<button type="button" name="ok_button" id="ok_button" >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();
}
CodePudding user response:
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:
$.ajax({
type: 'DELETE',
url:"/admin/employees/destroy/" employee_id,
CodePudding user response:
To solve the problem I had to put csrf inside the meta:
<meta name="csrf-token" content="{{ csrf_token() }}" />
And use this at the beginning of the script:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>