I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.
While m
Generally I agree with the concept Kornel suggested except one thing.
Yes, Laravel's docs advice to use $.ajaxSetup, but it's not recommended since this method affects all the subsequent ajax requests. It is more correctly to set the ajax settings for each request. Though you can re-set stuff:
All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup()
If you use $.ajax(), it's more convenient to utilize either data property or headers. Laravel allows CSRF-token both as a request parameter or a header.
First, you add the following meta tag into the view
And then make an ajax request either way:
$.ajax({
url: "/your/url",
method: "POST",
data:
{
a: 'something',
b: 'something else',
_token: $('meta[name="csrf-token"]').attr('content')
},
datatype: "json"
});
OR
$.ajax({
url: "/your/url",
method: "POST",
data:
{
a: 'something',
b: 'something else',
},
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
datatype: "json"
});