Laravel CSRF Token Mismatch for AJax Request

Sovary October 21, 2022 584
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him