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...
Know that there is an X-XSRF-TOKEN cookie that is set for convenience. Framework like Angular and others set it by default. Check this in the doc https://laravel.com/docs/5.7/csrf#csrf-x-xsrf-token You may like to use it.
The best way is to use the meta, case the cookies are deactivated.
Here the recommended meta way (you can put the field any way, but meta is quiet nice):
Note the use of
decodeURIComponent()
, it's decode from uri format which is used to store the cookie. [otherwise you will get an invalid payload exception in laravel].Here the section about the csrf cookie in the doc to check : https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token
Also here how laravel (bootstrap.js) is setting it for axios by default:
you can go check
resources/js/bootstrap.js
.And here read cookie function:
You should include a hidden CSRF (cross site request forgery) token field in the form so that the CSRF protection middleware can validate the request.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually makin gthe requests to the application.
So when doing ajax requests, you'll need to pass the csrf token via data parameter. Here's the sample code.
The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:
In header
In script
I actually had this error and could not find a solution. I actually ended up not doing an ajax request. I don't know if this issue was due to this being sub domain on my server or what. Here's my jquery.
So I actually set up an anchor to go to my API rather than doing a post request, which is what I figure most applications do.
I think is better put the token in the form, and get this token by id
And the JQUery :
this way, your JS don't need to be in your blade files.
You have to add data in your ajax request. I hope so it will be work.