Home > Backend Development > PHP Tutorial > How to Fix 'CSRF token mismatch for AJAX POST Request' in Laravel?

How to Fix 'CSRF token mismatch for AJAX POST Request' in Laravel?

DDD
Release: 2024-12-10 07:51:14
Original
819 people have browsed it

How to Fix

Resolving CSRF Token Mismatch for AJAX POST Requests in Laravel

When making AJAX POST requests in Laravel, it's essential to include the CSRF token to prevent Cross-Site Request Forgery attacks. In this article, we'll address the "CSRF token mismatch for ajax POST Request" issue.

Problem Description

You're attempting to delete data from a database through an AJAX request. Your HTML includes links that trigger the deletion upon clicking. The corresponding AJAX code sends a POST request to a specific URL. However, the deletion fails, and you receive a "CSRF token mismatch" error.

Solution

To resolve this issue, you must include the CSRF token in your AJAX request. This can be done by adding the following line to your data parameter:

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }
Copy after login

where id represents the ID of the record you're trying to delete. This token ensures that the server verifies the request before performing the deletion operation.

Updated AJAX Code

Here's the updated AJAX code with the CSRF token included:

$('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;
}
});
Copy after login

By including the CSRF token in your AJAX request, you ensure that the request is validated by the server, and the deletion operation will succeed without the "CSRF token mismatch" error.

The above is the detailed content of How to Fix 'CSRF token mismatch for AJAX POST Request' in Laravel?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template