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