Posts Learn Components Snippets Categories Tags Tools new About
/

How to Fix Laravel CSRF Token Mismatch for Ajax POST Request

Learn how to fix Laravel CSRF token mismatch for Ajax Post request in for jQuery, Axios and any other Javascript HTTP request client the easy way

Created on Nov 13, 2021

7 views

To fix Laravel CSRF token mismatch for Ajax POST request you need to specify the CSRF token in the AJAX request header. Let's get started by adding the "csrf-token" meta tag in the head section of the HTML code.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
Once you have placed that now you can reference it to the Ajax header for your HTTP request codes.
<meta name="csrf-token" content="{{ csrf_token() }}">

jQuery CSRF_TOKEN setup


If you are using jQuery to perform your Ajax then you can specify your code as follows.
$.ajax({
  url : "YOUR_API_URL_HERE",
  method:"post",
  data : {
    "_token": @json(csrf_token()),
  },  
  ...
});

Axios CSRF_TOKEN setup


By default Laravel ships Axios HTTP support so you have CSRF_TOKEN support already out of the box. If you are curious below is the code.
window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

AlpineJS, Native JS Fetch and etc


For AlpineJS and any regular JS applications, you can also make use of "fetch()" API. Do refer to the code below for the full code example.
fetch('YOUR_API_URL_HERE', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': @json(csrf_token()), },
    body: JSON.stringify(this.formData)
})
.then(() => {
    console.log('it works! yay')
})
.catch(() => {
    console.log('there\'s something error here')
})
Do note to update "YOUR_API_URL_HERE" to your API endpoint.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)