Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lara_dev's avatar

CSRF token mismatch exception in ajax post request in laravel 5.3 on localhost

I am newbie to laravel. I am using laravel 5.3 on localhost and i am posting data to controller function using ajax post request. I have integrated the CSRF token like this

inside the head section of master template

The after including jquery i add this script

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

i am sending data on button click like this

$.ajax({ type: "POST", url: './add_to_cart', data: {id:prod_id,name: name,price:price}, success: function( msg ) {

}

});

the first call goes right ,no error. But after the first call each call return error

TokenMismatchException in VerifyCsrfToken.php line 67

0 likes
11 replies
duka's avatar

You should set header (token) after url. Like this:

$.ajax({ type: "POST", url: './add_to_cart', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: {id:prod_id,name: name,price:price}, success: function( msg ) { } });

1 like
lara_dev's avatar

@duka ,i have tried this but still the same error TokenMismatchException in VerifyCsrfToken.php line 67: Token is generating in console like this https://www.screencast.com/t/gntfBMuhlLf

also the request is showing 500 error in console. Every thing was running fine.Suddenly this token mismatch exception occur.

SaeedPrez's avatar

@lara_dev

Add below code do your App\Http\Middleware\VerifyCsrfToken.php, it will display the expected token and the received token when CSRF fails..

    public function handle($request, \Closure $next)
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }

        // Dumps and dies with tokens upon mismatch
        dd(
            $sessionToken = $request->session()->token(),
            $request->input('_token') ?: $request->header('X-CSRF-TOKEN')
        );

        throw new TokenMismatchException;
    }
lara_dev's avatar

@SaeedPrez I can see the exception in ajax call response,"it is token mismatch exception" i need to fix the cause of the exception.

lara_dev's avatar

This is my route.Is there any thing wrong with route? Route::post('/add_to_cart', 'HomeController@add_to_cart')

Snapey's avatar

sounds like somethig wrong with session persistence

Do you have other functionality that shows sessions are working ok?

Also, using network tools in your browser check that session token and csrf token sent to the server are the same on request #1 and request #2

lara_dev's avatar

@SaeedPrez tried your code and this is the response

"milJ88tCCq3aqyKmHndPRyXsA0tqTxMhp4NUaC6h"

"oyh7hNBqMe77pQUM5vdHkH6Jfdlzy64MMDjJINT7" it means both tokens are different

lara_dev's avatar

@Snapey .I have just checked cookies section in google chrome and i have seen that first call is including token but second call have no token .Have a look at these screenshots 1:-screencast.com/t/2ILsMlDCZ9i 2:-screencast.com/t/mbQLfYLCjRN

lara_dev's avatar

After carefully reviewing my code .I found this piece of code was doing this. Session::flush(); after removing this issue solved. Thanks all for their effort

Snapey's avatar

in screenshot 1 it shows that the tokens you got back are different to the ones you sent, so Laravel has regenerated the session (or started a new one)

The missing token on the second screenshot is the reply containing the token mismatch so it makes no sense to send you another token.

Your browser spots that the session token changed on the first request and uses the new session token on the second. Jquery has also substituted the csrf token for the new one also, so i'm puzzled? I don't know if Laravel is expecting the first csrf token or the replacement?

Please or to participate in this conversation.