Milind Daraniya

How to pass a CSRF token with an Ajax request in Laravel!

Published August 7th, 2023 11 min read

Laravel provides built-in CSRF protection to guard against cross-site request forgery attacks. When making Ajax requests, it's essential to include the CSRF token to ensure the request is authenticated. Let's go through the steps to pass the CSRF token with an Ajax request in Laravel:

Step 1: Include the CSRF Token in Your Layout or Blade Template

  • In your main layout file or blade template (e.g., app.blade.php), add the following meta tag within the <head> section:
<meta name="csrf-token" content="{{ csrf_token() }}">

Step 2: Obtain the CSRF Token in Your JavaScript

  • In your JavaScript code, retrieve the CSRF token value from the meta tag you added in the previous step. You can use the $('meta[name="csrf-token"]').attr('content') jQuery selector to accomplish this.

Step 3: Pass the CSRF Token with Ajax Requests

  • When making an Ajax request, include the CSRF token in the request headers. You can use the beforeSend option of the Ajax call to set the appropriate headers. Here's an example using jQuery:
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '/your-endpoint',
    type: 'POST',
    data: {
        // Your request data
    },
    success: function(response) {
        // Handle the response
    },
    error: function(xhr) {
        // Handle errors
    }
});

By setting up the headers object with the CSRF token in $.ajaxSetup(), all subsequent Ajax requests will automatically include the token in their headers.

💡 Remember to adjust the url and request data (data property) according to your specific endpoint and requirements.

Protect your Ajax requests from cross-site request forgery attacks by passing the CSRF token in Laravel!