Home > Backend Development > PHP Tutorial > How to Solve Laravel's 'csrf_token mismatch' Error in AJAX POST Requests?

How to Solve Laravel's 'csrf_token mismatch' Error in AJAX POST Requests?

Susan Sarandon
Release: 2024-12-14 16:12:11
Original
671 people have browsed it

How to Solve Laravel's

Handling CSRF Token Mismatch in Laravel's Ajax POST Requests

When attempting to delete data from a database using an Ajax POST request, developers may encounter a "csrf_token mismatch" error. This issue arises when the Laravel framework employs Cross-Site Request Forgery (CSRF) protection, and the incoming request lacks a valid CSRF token.

To rectify this issue, it is crucial to incorporate a data parameter in the Ajax request and include both the "_token" and "id" values. The "_token" value is a CSRF token that prevents unauthorized requests, while the "id" value identifies the record to be deleted.

The revised Ajax code below:

$('body').on('click', '.delteadd', function (e) {
    e.preventDefault();
    if (confirm('Are you sure you want to Delete Ad ?')) {
        var id = $(this).attr('id');
        $.ajax({
            method: "POST",
            url: "{{url()}}/delteadd",
            data: {
                "_token": "{{ csrf_token() }}",
                "id": id
            }
        }).done(function( msg ) {
            if(msg.error == 0){
                alert(msg.message);
            }else{
                alert(msg.message);
            }
        });
    } else {
        return false;
    }
});
Copy after login

By adding this data parameter, the Ajax request ensures that the correct CSRF token and data are included, bypassing the "csrf_token mismatch" error and allowing successful data deletion from the database.

The above is the detailed content of How to Solve Laravel's 'csrf_token mismatch' Error in AJAX POST Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template