Home / Snippets / How to Fix Laravel CSRF Token Mismatch for Ajax POST Request
How to Fix Laravel CSRF Token Mismatch for Ajax POST Request cover

How to Fix Laravel CSRF Token Mismatch for Ajax POST Request

1.4K

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this