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...
Add an
id
to themeta
element that holds the tokenAnd then you can get it in your Javascript
For Laravel 5.8, setting the csrf meta tag for your layout and setting the request header for csrf in ajax settings won't work if you are using ajax to submit a form that already includes a
_token
input field generated by the Laravel blade templating engine.You must include the already generated csrf token from the form with your ajax request because the server would be expecting it and not the one in your meta tag.
For instance, this is how the
_token
input field generated by Blade looks like:You then submit your form with ajax like this:
The csrf token in the meta header is only useful when you are submitting a form without a Blade generated
_token
input field.if you are using jQuery to send AJAX Posts, add this code to all views:
Laravel adds a XSRF cookie to all requests, and we automatically append it to all AJAX requests just before submit.
You may replace getCookie function if there is another function or jQuery plugin to do the same thing.
If you are using template files, than you can put your
meta
tag in the headsection
(or whatever you name it) which contain yourmeta
tags.Next thing, you need to put the
headers
attribute to yourajax
(in my example, I am usingdatatable
with server-side processing:Here is the full
datatable
ajax example:After doing this, you should get
200 status
for yourajax
request.I just added
headers:
in ajax call:in view:
ajax function:
in controller:
in routes.php