Token Mismatch Error in AJAX
Introduction#
I have analyzed that ratio of getting TokenMismatch Error is very high. And this error occurs because of some silly mistakes. There are many reasons where developers are making mistakes. Here are some of the examples i.e No _token on headers, No _token passed data when using Ajax, permission issue on storage path, an invalid session storage path.
Setup Token on Header
Set the token on <head>
of your default.blade.php
.
<meta name="csrf-token" content="{{csrf_token()}}">
Add ajaxSetup
on the top of your script, that will be accessible to everywhere. This will set headers on each ajax
call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});