Laravel csrf token mismatch for ajax POST Request

Laravel requires CSRF tokens for AJAX POST requests. Fix 'token mismatch' by: 1) Set headers globally with $.ajaxSetup(), 2) Include _token in data, 3) Add hidden @csrf in forms, or 4) Use @json(csrf_token()). Recommended: Method 1 (headers) for cleaner separation. Ensure meta tag <meta name='csrf-token'> exists in layout.

Laravel csrf token mismatch for ajax POST Request Image

When making AJAX POST requests in Laravel, you'll often encounter "CSRF token mismatch" errors. This happens because Laravel requires a CSRF token for all POST requests to protect against cross-site request forgery attacks. Here are several ways to handle this:

Make sure your <meta name="csrf-token"> tag exists in your main layout:

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

Method 1: Include CSRF Token in AJAX Headers (Recommended)

This is the cleanest approach that keeps your token separate from your request data:

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

// Now all AJAX requests will automatically include the token
$.ajax({
    type: 'POST',
    url: '/your-route',
    data: {
        key: 'value'
    },
    success: function(response) {
        console.log(response);
    }
});

Method 2: Include Token in Request Data

You can pass the token directly in your request data:

$.ajax({
    type: 'POST',
    url: '/your-route',
    data: {
        _token: $('meta[name="csrf-token"]').attr('content'),
        key: 'value'
    },
    success: function(response) {
        console.log(response);
    }
});

Method 3: Add Hidden Inputs in Forms

For form submissions, include a hidden CSRF field:

<form id="myForm">
    @csrf
    <!-- other form fields -->
    <input type="text" name="username">
</form>

<script>
    $('#myForm').submit(function(e) {
        e.preventDefault();
        
        $.ajax({
            type: 'POST',
            url: '/your-route',
            data: $(this).serialize(),
            success: function(response) {
                console.log(response);
            }
        });
    });
</script>

Method 4: Using Laravel's @json Directive

A clean way to pass the token without modifying meta tags:

$.ajax({
    type: 'POST',
    url: '/your-route',
    data: { 
        _token: @json(csrf_token()),
        key: 'value'
    },
    success: function(response) {
        console.log(response);
    }
});

Best Practices

  1. Method 1 (headers approach) is generally recommended as it:
    • Keeps tokens separate from request data
    • Works for all AJAX requests after setup
    • Follows common HTTP header conventions
  2. Make sure your <meta name="csrf-token"> tag exists in your main layout:

    <meta name="csrf-token" content="{{ csrf_token() }}">
  3. For API routes, consider using the api middleware group which doesn't require CSRF protection.

Happy Coding! 😊

Do you Like?