jqueryajaxlaravelcsrf-protection

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

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

The after including jquery i add this script

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

      });
      console.log($('meta[name="csrf-token"]').attr('content'));
    });
  </script>

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:

Here is the error screenshot: error screenshot


Solution

  • 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 specially @Naveen Kumar