Ashish Singh Ashish Singh - 6 months ago 146
jQuery Question

Laravel csrf token mismatch for ajax POST Request

I am trying to delete data from database via ajax.

HTML:

@foreach($a as $lis)
//some code
<a href="#" class="delteadd" id="{{$lis['id']}}">Delete</a>
//click action perform on this link
@endforeach


My ajax code:

$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
var id = $(this).attr('id');
$.ajax({
method: "POST",
url: "{{url()}}/delteadd",
}).done(function( msg ) {
if(msg.error == 0){
//$('.sucess-status-update').html(msg.message);
alert(msg.message);
}else{
alert(msg.message);
//$('.error-favourite-message').html(msg.message);
}
});
} else {
return false;
}
});


This is my query to fetch data from database...

$a = Test::with('hitsCount')->where('userid', $id)->get()->toArray();


But when i click on Delete link data not deleted and show csrf_token mismatch...

Answer

You have to add data in your ajax request. I hope so it will be work.

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }