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

pn523's avatar
Level 2

TokenMismatchException in VerifyCsrfToken.php line 46 on one ajax request on done of another

I get TokenMismatchException when I make another ajax request from done of first one in jquery in laravel-5.0. I tried different Browsers but it yields to same output.

0 likes
35 replies
pn523's avatar
Level 2
            var setting = {
                    url : 'http://localhost/enduewitapi/login',
                    type : 'GET',
                    dataType : 'json',
                    data : data,
                };
                setting.done = function(data,textStatus,jqXHR){
                    alert("is_Numbers");
                    alert("First Done");
                    var dataOne = {
                        dataOne : data
                    };
                    gen_ajax(sessionPath, 'POST', dataOne,
                        function(data, textStatus, jqXHR){
                            alert("Second ajax request successfull");
                            console.log("Secondajax request successful");
                        },
                        function(jqXHR, textStatus, errorThrown){
                            alert("fail second ajax request");
                            console.log(errorThrown);
                        },
                        function(jqXHR,textStatus){}
                    );
                },
                setting.fail = function(jqXHR,textStatus,errorThrown){
                    alert(jqXHR.status);
                    console.log(errorThrown);
                },
                setting.always = function(jqXHR,textStatus){}
                Apiajax(setting);
            }
Cronix's avatar

You don't show whether you're sending the csrf token or not. Is it in data?

Snapey's avatar

The first one works because its a GET request. CSRF is not used in GET. Most likely you just are not sending the token.

pn523's avatar
Level 2

I am sending in token in head section.

pn523's avatar
Level 2
  1. Okay, one thing that i did wrong was that i posted the data to api as 'GET' but it was post, i changed it now.
  2. I had already included meta tag for 'CSRF-token' in Head section.
  3. I had already included $.ajaxSetup in ajax function called 'ApIajax' according to the docs.

BUT I AM STILL GETTING TokenMismatchException and an internal error '500' error.

Snapey's avatar

I had already included meta tag for 'CSRF-token' in Head section.

putting the token in the head of the view does not mean it gets sent with the post.

you need to include with the data

'_token': $('meta[name="csrf-token"]').attr('content') or similar

pn523's avatar
Level 2

I tried both ways :

  1. Included X-CSRF-TOKEN in the headers in $.ajaxSetup.
  2. sent the token included with data.

Still getting '500' error and 'TokenMismatchException'.

pn523's avatar
Level 2

I also tried by running :

  1. php artisan clear:cache 2)php artisan clear-compiled

But no change.Any Suggestions ??

Snapey's avatar

1st step ALWAYS - check what is being posted to the server

use the browser dev tools, network tab, make the post then click on the entry and check the request data

pn523's avatar
Level 2

This is being posted to the server :

_token : ts3tMDrxJS7BfADZ5LB9ovYyFodK2F4xlWUmBTyb emailOrmob : 1234567890 rememberme : true userPassword : qazwsxe

I am using chrome and firefox(Developer Edition).

I get following in response of network tab :

1/1 TokenMismatchException in compiled.php line 2440:

pn523's avatar
Level 2

When i disabled : 'App\Http\Middleware\VerifyCsrfToken' midleware in 'App\Http\kernel.php' in 'api' and my 'main project' , everything works.

But of course not verifying is not good idea.

Help is highly appreciated.

Snapey's avatar

have you logged in since you first got the token in the client?

It will obviously change if the session is regenerated.

pn523's avatar
Level 2

No, i did not logged in , i did not setup session yet. I sent the token with the data, but it did not work as stated earlier.

Snapey's avatar

Session is required to persist the token at the server side.

pn523's avatar
Level 2

I tried with sessions but same tokenmismatchexception occurs, again if i disable token middleware it works. I also digged in to the code of the middleware and tried, but no matter what ever I do, it just gives me same error over and over again.

Snapey's avatar

because the token does not match. yes of course disabling the middleware works.

describe your application, and show some of the view code?

Where do you get the token from?

pn523's avatar
Level 2
    {{-- CSRF Token --}}
 <input type="text" name="_token" value="{{ csrf_token() }}">
 <div class="form-group">
  <label for="emailOrmob">Email or Mobile</label>
  <input data-bind="value:emailOrmob" class="form-control mob-error" id="emailOrmob" placeholder="Enter Email or Mobile number here">
 </div>
 <div class="form-group">
  <label for="password">Password</label>
  <input data-bind="value:userPassword" type="password" class="form-control pass-error" id="userPassword" placeholder="Enter Password here">
</div>
 <div class="checkbox">
  <label>
  <input data-bind="checked:rememberme" type="checkbox">Remember me
 </label>
</div>
<button data-bind="click:loginClicked" type="submit" class="btn btn-primary btn-lg" style="display: flex;margin:auto;">LogIn</button>
</form>
pn523's avatar
Level 2

I do not why but the code above is not showing the opening form tag, method is 'POST'.

pn523's avatar
Level 2
{{ $title }}
        {{-- For Extra Small Devices --}}
        <div class="hidden-lg hidden-md hidden-sm col-xs-12" style="" id="">
            <div class="col-lg-12 text-white">HI</div>
            <div class="col-lg-12" style="background-color: rgba(0,0,0,0.85); height: 70px;" id="overlay"></div>
        </div>

        {{-- For Small, Medium and Large Devices --}}
        <div class="col-lg-12 col-md-12 col-sm-12 hidden-xs no-padding">
            
            {{-- Toster Message --}}
            <div class="col-lg-3 col-md-3 col-sm-3 no-padding toster white font-16" id="tosterDisplay" style="display: none;">
            <p class="margin-bottom-0" id="tosterid">Hi it is successful</p>
            </div>

            {{-- Header --}}
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding height-40 font-2em bg-color-329FFF position-fixed z-index-10">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 height-40">
                    <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 no-padding">
                        <p class="margin-bottom-0 text-white height-40" id="brand-name">Enduewit
                        </p>
                    </div>  
                    <div class="col-lg-8 col-md-8 col-sm-6 col-xs-8">
                        <p class="horizontal-middle margin-0" id="menu">Explore
                            <span class="caret rotate-270 margin-top-20 margin-left-10"></span>
                        </p>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-1">
                        <button id="loginBtn" type="button" class="text-white pull-right background-transparent font-22 margin-top-5" data-toggle="modal" data-target="#loginModal">LogIn</button>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-1">
                        <button id="signUpBtn" type="button" class="text-white pull-left margin-top-5 background-transparent font-22 margin-top-5">Signup</button>
                    </div>
                </div>
            </div>

            <div class="position-absolute margin-top-50">
                <img src="{{ config('path.images.home-bg-image') }}" alt="Image" id="home-bg-img">
            </div>

            <div class="position-relative overlay margin-top-50">
                <div class="col-lg-12 col-md-12 col-sm-12" class="homeLinks margin-top-50" id="shortcutOne">
                    <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 margin-left-100" id="linkOne">
                        <a href="javascript:void(0)" class="homeLinks">
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                            cillum dolore eu fugiat nulla pariatur.</p>
                        </a>
                    </div>
                    <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 pull-right margin-right-100" id="linkTwo">
                        <a href="javascript:void(0)" class="homeLinks">
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                            cillum dolore eu fugiat nulla pariatur.</p>
                        </a>
                    </div>
                </div>
                <div class="col-lg-12 col-md-12 col-sm-12" class="homeLinks margin-top-50" id="shortcutTwo">
                    <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 margin margin-left-100" id="linkThree">
                        <a href="javascript:void(0)" class="homeLinks">
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                            cillum dolore eu fugiat nulla pariatur.</p>
                        </a>
                    </div>
                    <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 pull-right margin-right-100" id="linkFour">
                        <a href="javascript:void(0)" class="homeLinks">
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                            cillum dolore eu fugiat nulla pariatur.</p>
                        </a>
                    </div>
                </div>
            </div>
            
            {{-- Modal Code --}}
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            
                {{-- Login Modal --}}
                <div id="loginModal" class="modal fade col-lg-12 col-md-12 col-sm-12 col-xs-12" role="dialog">
                  <div class="modal-dialog">

                     {{-- Modal content --}}
                        <div class="modal-content">
                          <div class="modal-header text-center border-bottom-blue">
                            <button type="button" class="close pull-right" data-dismiss="modal">&times;</button>
                            <h2 class="modal-title">Login</h2>
                          </div>
                          <div class="modal-body no-padding">
                            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 margin-top-20" id="main">
                                <form method='POST' action="/">
                                    {{-- CSRF Token --}}
                                    <input type="text" name="_token" value="{{ csrf_token() }}">
                                    <div class="form-group">
                                        <label for="emailOrmob">Email or Mobile</label>
                                        <input data-bind="value:emailOrmob" class="form-control mob-error" id="emailOrmob" placeholder="Enter Email or Mobile number here">
                                    </div>
                                    <div class="form-group">
                                        <label for="password">Password</label>
                                        <input data-bind="value:userPassword" type="password" class="form-control pass-error" id="userPassword" placeholder="Enter Password here">
                                    </div>
                                    <div class="checkbox">
                                        <label>
                                          <input data-bind="checked:rememberme" type="checkbox">Remember me
                                        </label>
                                    </div>
                                    <button data-bind="click:loginClicked" type="submit" class="btn btn-primary btn-lg" style="display: flex;margin:auto;">LogIn</button>
                                </form>
                            </div>
                          </div>
                          <div class="modal-footer"></div>
                        </div>
                  </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="{{ config('path.js.jquery') }}"></script>
<script type="text/javascript" src="{{ config('path.js.bootstrap') }}"></script>
<script type="text/javascript" src="{{ config('path.js.knockout') }}"></script>
<script type="text/javascript" src="{{ config('path.js.common') }}"></script>
<script type="text/javascript" src="{{ config('path.js.home') }}"></script>
<script type="text/javascript">
    var sessionPath =   "{{ action('SessionController@session') }}";
    var cookiePath  =   "{{ action('CookieController@setCookie') }}";
</script>
pn523's avatar
Level 2

I don't know why is laracast is not showing my entire code , Any Suggestions ??

Snapey's avatar

yes, you have to put three backticks ``` on a line before and after the code block

pn523's avatar
Level 2
<html lang="{{ App::getLocale() == 'en' }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <title>{{ $title }}</title>
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.bootstrap') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.bootstrap-map') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.font') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.spacing') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.common') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.toster') }}">
    <link rel="stylesheet" type="text/css" href="{{ config('path.css.home') }}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            
            {{-- For Extra Small Devices --}}
            <div class="hidden-lg hidden-md hidden-sm col-xs-12" style="" id="">
                <div class="col-lg-12 text-white">HI</div>
                <div class="col-lg-12" style="background-color: rgba(0,0,0,0.85); height: 70px;" id="overlay"></div>
            </div>

            {{-- For Small, Medium and Large Devices --}}
            <div class="col-lg-12 col-md-12 col-sm-12 hidden-xs no-padding">
                
                {{-- Toster Message --}}
                <div class="col-lg-3 col-md-3 col-sm-3 no-padding toster white font-16" id="tosterDisplay" style="display: none;">
                <p class="margin-bottom-0" id="tosterid">Hi it is successful</p>
                </div>

                {{-- Header --}}
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding height-40 font-2em bg-color-329FFF position-fixed z-index-10">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 height-40">
                        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 no-padding">
                            <p class="margin-bottom-0 text-white height-40" id="brand-name">Enduewit
                            </p>
                        </div>  
                        <div class="col-lg-8 col-md-8 col-sm-6 col-xs-8">
                            <p class="horizontal-middle margin-0" id="menu">Explore
                                <span class="caret rotate-270 margin-top-20 margin-left-10"></span>
                            </p>
                        </div>
                        <div class="col-lg-1 col-md-1 col-sm-2 col-xs-1">
                            <button id="loginBtn" type="button" class="text-white pull-right background-transparent font-22 margin-top-5" data-toggle="modal" data-target="#loginModal">LogIn</button>
                        </div>
                        <div class="col-lg-1 col-md-1 col-sm-2 col-xs-1">
                            <button id="signUpBtn" type="button" class="text-white pull-left margin-top-5 background-transparent font-22 margin-top-5">Signup</button>
                        </div>
                    </div>
                </div>

                <div class="position-absolute margin-top-50">
                    <img src="{{ config('path.images.home-bg-image') }}" alt="Image" id="home-bg-img">
                </div>

                <div class="position-relative overlay margin-top-50">
                    <div class="col-lg-12 col-md-12 col-sm-12" class="homeLinks margin-top-50" id="shortcutOne">
                        <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 margin-left-100" id="linkOne">
                            <a href="javascript:void(0)" class="homeLinks">
                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                cillum dolore eu fugiat nulla pariatur.</p>
                            </a>
                        </div>
                        <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 pull-right margin-right-100" id="linkTwo">
                            <a href="javascript:void(0)" class="homeLinks">
                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                cillum dolore eu fugiat nulla pariatur.</p>
                            </a>
                        </div>
                    </div>
                    <div class="col-lg-12 col-md-12 col-sm-12" class="homeLinks margin-top-50" id="shortcutTwo">
                        <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 margin margin-left-100" id="linkThree">
                            <a href="javascript:void(0)" class="homeLinks">
                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                cillum dolore eu fugiat nulla pariatur.</p>
                            </a>
                        </div>
                        <div class="col-lg-4 col-md-4 col-sm-5 col-xs-4 bg-white border-radius-15 padding-10 pull-right margin-right-100" id="linkFour">
                            <a href="javascript:void(0)" class="homeLinks">
                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                cillum dolore eu fugiat nulla pariatur.</p>
                            </a>
                        </div>
                    </div>
                </div>
                
                {{-- Modal Code --}}
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                
                    {{-- Login Modal --}}
                    <div id="loginModal" class="modal fade col-lg-12 col-md-12 col-sm-12 col-xs-12" role="dialog">
                      <div class="modal-dialog">

                         {{-- Modal content --}}
                            <div class="modal-content">
                              <div class="modal-header text-center border-bottom-blue">
                                <button type="button" class="close pull-right" data-dismiss="modal">&times;</button>
                                <h2 class="modal-title">Login</h2>
                              </div>
                              <div class="modal-body no-padding">
                                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 margin-top-20" id="main">
                                    <form method='POST' action="/">
                                        {{-- CSRF Token --}}
                                        <input type="hidden" name="_token" value="{{ csrf_token() }}" />
                                        <div class="form-group">
                                            <label for="emailOrmob">Email or Mobile</label>
                                            <input data-bind="value:emailOrmob" class="form-control mob-error" id="emailOrmob" placeholder="Enter Email or Mobile number here">
                                        </div>
                                        <div class="form-group">
                                            <label for="password">Password</label>
                                            <input data-bind="value:userPassword" type="password" class="form-control pass-error" id="userPassword" placeholder="Enter Password here">
                                        </div>
                                        <div class="checkbox">
                                            <label>
                                              <input data-bind="checked:rememberme" type="checkbox">Remember me
                                            </label>
                                        </div>
                                        <button data-bind="click:loginClicked" type="submit" class="btn btn-primary btn-lg" style="display: flex;margin:auto;">LogIn</button>
                                    </form>
                                </div>
                              </div>
                              <div class="modal-footer"></div>
                            </div>
                      </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="{{ config('path.js.jquery') }}"></script>
    <script type="text/javascript" src="{{ config('path.js.bootstrap') }}"></script>
    <script type="text/javascript" src="{{ config('path.js.knockout') }}"></script>
    <script type="text/javascript" src="{{ config('path.js.common') }}"></script>
    <script type="text/javascript" src="{{ config('path.js.home') }}"></script>
    <script type="text/javascript">
        var sessionPath =   "{{ action('SessionController@session') }}";
        var cookiePath  =   "{{ action('CookieController@setCookie') }}";
    </script>
</body>
</html>```
Snapey's avatar

ok, so the issue (and I did not notice the function of your 1st ajax call), is that your first call is a login request.

If this is successful then a new session will be generated and the second call will always fail if trying to use the same token.

Either have a rethink and reload the page after login, or send the new csrf token back to the client as part of the 1st response.

pn523's avatar
Level 2

I tried sending the new token back to the client but my first ajax request did not succeed, it showed TokenmismatcheException.

Snapey's avatar

I don't actually think you can do what you want. After login you must reload the page to get the new session.

You must rethink the design.

Cronix's avatar

@snapey Just thinking out loud here... Do you think it's possible to just pass back the token generated by the new session using \Session::token() when logging in, and return that as part of your ajax data, and then update the _token on the page, or in the header if using a token meta tag? The session is created upon a successful login, so I'm guessing the new token is created as part of that session. Then use that new token on subsequent ajax calls? Again I haven't tried this, it just seems theoretically plausible.

Edit: I didn't see that you kind of suggested that

or send the new csrf token back to the client as part of the 1st response

Snapey's avatar

@cronix I thought of that at first, but along with the new csrf token, the session cookie will also be different. The new token could be returned but I think it would belong to the wrong session ?

santhusurya's avatar

Please follow below method to setup "CSRF-Token" only once on a page for any number of ajax calls.

<meta name="csrf-token" content="{{ csrf_token() }}">

Place above snippet in the head section as mentioned below on the page on which you are using ajax calls.

<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head> 

Then place this below code snippet only once before initiating any ajax calls.

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

This above code snippet will configure every ajax call with predefined CSRF - header with required valid CSRF token.

Next

Please or to participate in this conversation.