Laravel CSRF Token Mismatch for AJax Request

Sovary October 21, 2022 350
2 minutes read

Each active user session managed by Laravel application will automatically generates CSRF token. The token is used to verify user is the one who making the request to the server application. Today we will show you how to fixed mismatch CSRF token requested by ajax. The below example, you will learn how to make Ajax request without mismatch CSRF token response from server.

Basically if you create submit form request in blade file you may put a directive @csrf and the form will submit find with reload page. But in case we use ajax making request to the server then the server will check CSRF token which send from client has not found or invalid, the server will respond 419 status code mismatch CSRF token.

CSRF Token Mismatch for Ajax Request

  • Solution 1 - Add Token in Request Header
  • Solution 2 - Add Token in Data Request

Solution 1 - Add Token in Request Header

In blade file, in header HTML element should add an element to store CSRF token for example we create new meta element to hold to value of CSRF token.

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

The same file when you making Ajax request don't forget append token to request header. See below ajax code in your laravel project.

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

You may also pass value CSRF token directly to Ajax header without access via CSS query selector

$.ajaxSetup
({
  headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
  }
});
 
$.ajax
({
   // Ajax code here
});

Solution 2 - Add Token in Data Request

Another solution when you found issue like CSRF token mismatch in your laravel app, you can following below code by adding CSRF token to data property name "_token" the problem will solved.

I prefer option pass token value directly in Javascript and you can make request AJax and submit token via AJax form as below:

$.ajax({
    type: "POST",
    url: '/your_url_here',
    data: 
        {
           field1: "value1",
           field2: "value2",
           _token: '{{csrf_token()}}' 
        },
    success:(data) =>
    {
       console.log(data);
    },
    error: err)=>
    {
       console.log(err);
    },
});

Hope you find one of these solution help you to complete your project today. Have a nice day!

You might also like...

Laravel  PHP  Laravel 9 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him