I want to delete data from a database with an ajax
call but it’s showing an error.
CSRF token mismatch
In header:
<meta name="csrf-token" content="{{ csrf_token() }}">
In blade:
<button class="deletePhoto" data-id="{{ $photo->id }}" data-token="{{ csrf_token() }}">Delete</button>
AJAX call:
$('.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:
public function destroy($id) { $photo = Photo::find($id); $photo->delete(); }
Advertisement
Answer
This is what I usually do : [AJAX CALL]
$.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); } })