I'm using Laravel 5.2 for my web application and I have a page with multiple ajax requests by the same event. In $.ajax, I set async: true, Sometimes it shows CSRF token Mismatch error and redirect to login page. However when I set Async: false in ajax, it works fine but it takes lots of time.
Please help me so that it does not show token mismatch error.
in your form create one hidden filed name _token you can use this helper method to generate field
{!! csrf_field() !!}
in javascript you have to fetch this field value
var token = $( "input[name='_token']" ).val();
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston",_token:token }
});
another way create hidden a span or div add data attribute to it
<div id="token" data-token="{{ csrf_token() }}"></div>
fetch in javascript data value
var token = $( "#token" ).data('token');
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston",_token:token }
});
You said you use
$.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } });
Maybe somewhere headers in request overrides, try to change it on
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name=_token]').attr('content') );
}
});
Please modify your url variable like so :
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',