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

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

Barbara Streisand
Release: 2024-12-10 09:07:13
Original
743 people have browsed it

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

Laravel CSRF Token Mismatch for Ajax POST Request: Troubleshooting and Solution

When performing an AJAX POST request in Laravel, you may encounter a CSRF (Cross-Site Request Forgery) token mismatch error. This error occurs when the CSRF token included in the request doesn't match the one stored in your session.

In your specific case, you're trying to delete data from the database via AJAX, but you're receiving a CSRF token mismatch error. To resolve this issue, you need to add the CSRF token to your AJAX request.

The CSRF token is a unique value generated by Laravel for each session. It helps prevent malicious requests from being made by external sources.

To add the CSRF token to your AJAX request, you can use the following code:

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

where id is the ID of the item you want to delete.

Remember to add this data object to your AJAX request options:

$.ajax({
    method: "POST",
    url: "{{url()}}/delteadd",
    data: {
        "_token": "{{ csrf_token() }}",
        "id": id
    }
}).done(function( msg ) {
    // Handle the response
});
Copy after login

This will ensure that the CSRF token is included in your request and the issue should be resolved.

The above is the detailed content of How to Resolve 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