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 }
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; } });
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!