jessiesanford's avatar

AJAX post requests cause Token Mismatch because the CSRF token changes.

I have spent weeks searching for a solution to this issue with no luck. I am running an application that utilizes a vast array of AJAX post requests to move and manipulate data. I have:

$.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});

But it does not work as the token randomly changes [see screenshot of a back end GET request retrieving the token] resulting in a Token Mismatch error indefinitely until I refresh the page. I have an error catching method in place to keep reloading the meta tag until the right token is found but it is insanely inefficient and hackish. Is there no solution to this madness?

Screenshot: https://gyazo.com/7ab04e78ef75a80cf2a34aac493bd41e

0 likes
6 replies
jessiesanford's avatar

Looked at that thread but it doesn't seem related to my issue. I'm talking about POST, I have a GET that retrieves the proper token to update the meta tag but that defeats the purpose.

jlrdw's avatar

That thread is talking about POST as well. If you look good there's answer.

jessiesanford's avatar

Yes but I have no problem performing the POST, it's just that for some reason the AJAX call causes the token to regenerate therefore on the client side the user no longer has the right token resulting in a TokenMismatch error, which shouldn't happen unless the user's session timed out (which is set to the default 120 minutes).

jlrdw's avatar

Make sure token has a name, and in that thread you see

$post._token = document.getElementsByName("_token")[0].value

if you are constantly repeating ajax request the server needs time to catch up, by using document.getElementsByName you are retrieving correct token for that request.

Slow down the rate you are performing ajax request. It's not instant, it still has to "travel" to the server.

Please or to participate in this conversation.