Home >Backend Development >PHP Tutorial >How to Fix Laravel's CSRF Token Mismatch Error in AJAX POST Requests?

How to Fix Laravel's CSRF Token Mismatch Error in AJAX POST Requests?

DDD
DDDOriginal
2024-12-09 11:49:09664browse

How to Fix Laravel's CSRF Token Mismatch Error in AJAX POST Requests?

Laravel CSRF Token Mismatch for AJAX POST Request

When attempting to delete data using an AJAX POST request from an HTML anchor element, you may encounter a "CSRF token mismatch" error if the request lacks the necessary security token.

Here's an example of an improved AJAX code that incorporates the mandatory data attribute:

$('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){
                //$('.sucess-status-update').html(msg.message);
                alert(msg.message);
            }else{
                alert(msg.message);
                //$('.error-favourite-message').html(msg.message);
            }
        });
    } else {
        return false;
    }
});

By including the request's token and ID in the data attribute, you ensure that CSRF protection operates as intended. This guarantees that the request is authentic and originates from your application.

The above is the detailed content of How to Fix Laravel's CSRF Token Mismatch Error in AJAX POST Requests?. 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