Home >Backend Development >PHP Tutorial >How to Solve Laravel's 'csrf_token mismatch' Error in AJAX POST Requests?
Handling CSRF Token Mismatch in Laravel's Ajax POST Requests
When attempting to delete data from a database using an Ajax POST request, developers may encounter a "csrf_token mismatch" error. This issue arises when the Laravel framework employs Cross-Site Request Forgery (CSRF) protection, and the incoming request lacks a valid CSRF token.
To rectify this issue, it is crucial to incorporate a data parameter in the Ajax request and include both the "_token" and "id" values. The "_token" value is a CSRF token that prevents unauthorized requests, while the "id" value identifies the record to be deleted.
The revised Ajax code below:
$('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){ alert(msg.message); }else{ alert(msg.message); } }); } else { return false; } });
By adding this data parameter, the Ajax request ensures that the correct CSRF token and data are included, bypassing the "csrf_token mismatch" error and allowing successful data deletion from the database.
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!