Home >Backend Development >PHP Tutorial >Laravel 5.5 Ajax Error 419: How to Fix CSRF Token Issues?

Laravel 5.5 Ajax Error 419: How to Fix CSRF Token Issues?

DDD
DDDOriginal
2024-12-06 13:48:17456browse

Laravel 5.5 Ajax Error 419: How to Fix CSRF Token Issues?

Laravel 5.5 Ajax Call Error: 419 (Unknown Status)

When performing an Ajax call in Laravel 5.5, you may encounter an error with the message "419 (unknown status)." This typically stems from an issue with the Cross-Site Request Forgery (CSRF) protection mechanism. Here's how to resolve this issue:

Ensure CSRF Token is Available

Laravel requires a CSRF token to prevent malicious requests from being executed. Ensure a CSRF token meta tag is present in the header section of your blade template:

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

Access CSRF Token in Ajax

Configure your Ajax request to automatically retrieve and include the CSRF token in the header:

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

Example Updated Code:

$('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");

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

      $.ajax({
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          success:function(response) {
               console.log(response);
          }
     });
  });

Additional Tip

Refer to the Laravel Documentation for more information on CSRF protection: https://laravel.com/docs/5.5/csrf

The above is the detailed content of Laravel 5.5 Ajax Error 419: How to Fix CSRF Token Issues?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn