I’ve got a form that has some fields that their values are loaded in by an ajax call to a controller after the first input is filled.
I have added the token as an input to my form with "@csrf" in my blade file.
To make the Ajax call I’m sending the CSRF token in the data section.
The first time I login my application and load the page where the form is located I get the "CSRF Token Mismatch" error when doing the Ajax call. If I reload the page normally with F5 key or just clicking the reload button on my browser, it works flawlessly.
What is producing this behaviour in my application and how can I fix it?
I know we can bypass this issue by disabling the token protection for this route, but that’s the last thing I want to do.
2
Answers
I figured out that I can make a GET call to my controller without having to care about the token. With that in mind I made the controller regenerate my session token and send it back to the view.
The token I just sent to the view will be used for the POST ajax calls and works perfect.
You must send CSRF Token into ajax headers. if you don’t have
<meta name="csrf-token" content="{{ csrf_token() }}" />
you can add this code inside of
<head></head>
tag in your html. after that you can send csrf token into headers ajax request like thisbut another way you can add to headers ajax directly like this