Shubham Sawant
Shubham Sawant

Reputation: 71

Message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}

I am A PHP developer and currently moving towards Laravel framework as per my task I have to complete the realtime table using ajax but I am sticking with an error which is CSRF token mismatch error please help me to resolve the error I am posting shortcode only

JAVA Script

<script>

 function getMessage() {
        $.ajax({
           //var data = {"_token": $('#token').val()},
           type:'POST',
           url:'/getMsg',
           headers: {'XSRF-TOKEN': $('meta[name="_token"]').attr('content')},
           success:function(data) {
              $("#msg").html(data.msg);
           }
           
        });
        
     }
    
  </script>

Route Path

Route::post('/getMsg','CustomerSearchController@doAjaxTest');

Controller code

public function doAjaxTest(){
    $msg = "<b>Message over ajax This test is Successful</b>.";
    return response()->json(array('msg'=> $msg), 200);
}

HTML CODE

<center>
 
 <input type = "hidden" name = "_token" value = '<?php echo csrf_token(); ?>'>
 <table>
 <tr>
 
 <td><label>Enter Place Name</label></td>
 <td><input type="text" class="form-control" id="placename" name="placename" placeholder="Name Of Place"/></td>
 </tr>
 <tr>
 <td>
 <input type="submit" value="Get Message" onclick="getMessage()" />
 </td>
 </tr>
 </table>

 <br>
 <!--
 <div class="panel panel-default table-responsive">
            <div id="dataTag"><b>All the Details according to department will be displayed</b></div>
            
      </div>
 -->
 <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>
  </center>

I don't know why it is showing me CSRF token mismatch when headers contain tokens once solved i can have some realtime action please help out

Upvotes: 5

Views: 23936

Answers (5)

bytzu
bytzu

Reputation: 1

Had a similar problem, try adding these lines in your local .env file

SANCTUM_STATEFUL_DOMAINS=localhost:81
SESSION_DOMAIN=localhost:81

Change the port to fit your local settings

Upvotes: 0

Yusup
Yusup

Reputation: 41

Try this

data: _token: '{{csrf_token()}}',

Upvotes: 0

Alexej Ks
Alexej Ks

Reputation: 1

If you have already configured headers and it still doesn't work, try creating a new key:

php artisan key:generate

Upvotes: 0

Hadayat Niazi
Hadayat Niazi

Reputation: 2470

make sure that you have the meta tag in your head of the view:

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

Then you can initialize it just once after loading the jQuery library, add this:

<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>

Try with solution

Upvotes: 4

I had a same problem. i changed APP_NAME in .env file to default value (Laravel). try it.

Upvotes: 1

Related Questions