

How To Fix Laravel CSRF Token Mismatch Error From AJAX Request
source link: https://www.codewall.co.uk/how-to-fix-laravel-csrf-token-mismatch-error-from-ajax-request/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How To Fix Laravel CSRF Token Mismatch Error From AJAX Request
As I’ve mentioned in previous posts about CSRF tokens, Laravel actively checks certain requests for CSRF tokens for validation. If this isn’t validated correctly, one of the most common errors you will receive is ‘CSRF token mismatch‘. The use-case in which you generally experience this mismatch error is during requests that are sent with AJAX or similar.
Let’s take the following JavaScript AJAX request for example.
$.ajax({
type: 'POST',
url: '/api/myApiUrl',
data: myObject
success: function (data) {
console.log(data);
}
});
This request, when executed will receive a response in the console that there is a CSRF token mismatch.
So, how do we fix it?
Well, there are a couple of methods and either one is perfectly fine and pretty much depends on your own preference.
But first of all, to ensure that you can reference the CSRF token in both your HTML file and JavaScript files alike, a meta tag must be present in your <head>
section.
To check this, have a look in your layout files where the <head> section is defined and look for the following code snippet –
<meta name="csrf-token" content="{{ csrf_token() }}">
If you cannot find it, then add it to the file.
Method 1
Adding a new AJAX ‘header’.
Add the following code snippet into your <script>
section, prior to the AJAX call.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
This snippet will pre-set the AJAX header by grabbing the csrf-token from the meta tag named csrf-token as explained earlier. It is the simplest way to go, especially if you have multiple AJAX calls assigned to different functionality like filters or buttons.
Method 2
Passing the token as a data property along with any other information that will be sent via AJAX.
Within the AJAX call itself, add another data property alongside the data that will be passed already.
$.ajax({ type: 'POST', url: '/api/myApiUrl', data: {"myObj": myObject, "_token": "{{ csrf_token() }}"}, success: function (data) { console.log(data); } });
Summary
And that is it, using either one of these methods will ensure that the CSRF token is always sent with your HTTP requests with AJAX or similar. These methods will rid the error of CSRF token mismatch and validate it correctly with Laravel every time.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK