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?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 02:44:13457browse

How to Solve Laravel's

Resolving CSRF Token Mismatch in Laravel AJAX POST Requests

When attempting to delete data from a database using an AJAX POST request in Laravel, you may encounter the error "CSRF token mismatch." This occurs because Laravel includes a CSRF token in all forms to protect against cross-site request forgery attacks.

Defining the AJAX Request

The provided HTML and AJAX code show a setup for deleting data:

HTML:

@foreach($a as $lis)
  //some code
  <a href="#">

AJAX Code:

$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
    var id = $(this).attr('id');
    $.ajax({
        method: "POST",
        url: "{{url()}}/delteadd",
        }).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;
}
});

Adding the CSRF Token

To resolve the "CSRF token mismatch" error, you must include the CSRF token in your AJAX request. This can be done by adding the following code to your request:

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }

Updated AJAX Code:

$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
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;
}
});

With this addition, your AJAX request will include the CSRF token and the data you need to perform the deletion operation.

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!

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