I want to delete data from a database with an ajax
call but it’s showing an error.
CSRF token mismatch
In header:
JavaScript
x
<meta name="csrf-token" content="{{ csrf_token() }}">
In blade:
JavaScript
<button class="deletePhoto" data-id="{{ $photo->id }}" data-token="{{ csrf_token() }}">Delete</button>
AJAX call:
JavaScript
$('.deletePhoto').click(function () {
var id = $(this).data('id');
var el = this;
$.ajaxSetup({
headers:{
'X_CSRF_TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
},
success: function () {
$(el).closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
})
Controller:
JavaScript
public function destroy($id)
{
$photo = Photo::find($id);
$photo->delete();
}
Advertisement
Answer
This is what I usually do : [AJAX CALL]
JavaScript
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
'_token': '{{ csrf_token() }}',
},
success: function () {
el.closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})