Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 CSRF Token Mismatch Ajax Request – Fixed

Last Updated on April 27, 2024 by

Laravel has built in CSRF token security to prevent CSRF token attacks via forms in Laravel applications.

When making an Ajax request from a form in your Laravel application, you did not add the CSRF token in the Ajax request header to prevent CSRF token mismatch errors.

Here are solutions to fix CSRF Token Mismatch Ajax Request error:

Step 1: Setup CSRF Token in Your Forms

Open your form views from resources/views/), make sure to include the CSRF token in the meta tag within the <head> section:

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

Step 2: Configure Ajax Requests to Include CSRF Token

When making Ajax requests, ensure that the CSRF token is included in the request headers. You can do this by retrieving the token from the meta tag and adding it to the headers of your Ajax requests

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

Step 3: Handle CSRF Token Mismatch Error

If there is a CSRF token mismatch, Laravel will throw a TokenMismatchException. You need to handle this error in your JavaScript code to inform the user and possibly refresh the CSRF token.

$(document).ajaxError(function(event, xhr, settings, error) {
    if (xhr.status === 419) {
        // CSRF token mismatch error
        // Display an error message or handle the error as needed
        console.error("CSRF token mismatch. Refreshing page...");
        location.reload();
    }
});

With the help of just 3 steps you can solve the CSRF token mismatch error that your Laravel 11 application is facing.

Leave a Comment