How To Fix Laravel CSRF Token Mismatch Error With AJAX Request

How To Fix Laravel CSRF Token Mismatch Error With AJAX Request

In this tutorial, we will see that if the CSRF token mismatch, then how will we have to fix it?

As you know, the CSRF token is to prevent any spam that we pass in the form by creating an input type field name CSRF token. This provides us with the security with which we submit any form.

But when we are sending CSRF token, we are getting some error {“status”:401,”message”:”invalid csrf token”}, so what will we do. give a most common errors you will receive is ‘CSRF token mismatch‘. and CSRF token invalid error is during requests that are sent with AJAX or similar.

Following JavaScript AJAX request for example:

$.ajax({
                type: 'POST',
                url:  '/api/myUrl',
                data: myObject
                success: function (data) {
                    console.log(data);
                }
});

Then, This request, when executed will receive a response in the console that there is a CSRF token mismatch (error: token mismatch).

So, how do we fix it? CSRF token mismatch.

Well, there are some ways on which we depend such as

First of all, to ensure that you can reference the CSRF token mismatch in both your HTML file and JavaScript files like a meta tag must be present in your <head> section.

To check this, have a look in your project layout files where the section is defined and look for the following code snippet –

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

If you cannot find it, then add it to the file.

Method 1. Adding a new AJAX ‘header’.

dd the following code snippet into your <script> section, prior to the AJAX call.

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

This snippet will pre-set the AJAX header. CSRF-token from the set meta tag named CSRF-token as explained earlier. if you have multiple AJAX calls assigned to different functionality like buttons in your set project.

Method 2. Passing the token as a data property

along with any other information like laravel token mismatch error that will be sent via AJAX in project.

Error token mismatch Within the AJAX call itself, add another data property alongside the data that will be passed already form. and fixed CSRF token mismatch to correct.

$.ajax({
    type: 'POST',
    url: '/api/myUrl',
    data: {"myObj": myObject, "_token": "{{ csrf_token() }}"},
    success: function (data) {
        console.log(data);
    }
});

Conclusion

using this code, we can fix any of the CSRF tokens every time. Will ensure your projects that the CSRF token is always sent with your HTTP requests with AJAX or similar. These methods will write the error of CSRF token mismatch and validate it correctly with the Laravel framework at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *