I'm using DropZone.js and laravel. When i try to delete a record with an AJAX request i get a response saying:
Whoops, looks like something went wrong. 1/1 TokenMismatchException in VerifyCsrfToken.php
var classElements = document.querySelectorAll("tr.ui-selected td.filename");
for(var x = 0;x < classElements.length;x++){
var result;
result = classElements[x].innerHTML;
var csrf = $('input[name=_token]').val();
$.ajax({
async: true,
type: "DELETE",
method: 'POST',
url: '../public/deletefile',
data: { filename: result, "_token": "{{ csrf_token() }}" },
success: function(response) {
$('#results').html(response);
}
});
This is the model:
public function deleteUserFiles(){
$userid = Auth::id();
$result = $_POST['result'];
$deletedRows = App\Models\File::where('filename', $result)->where('userid', $userid)->delete();
}
}
And the route:
Route::post('deletefile', 'UserFiles@deleteUserFiles');
What could be the problem?
I think the problem here is that you use csrf_token()
in loop. I think your JS code should look like this:
var classElements = document.querySelectorAll("tr.ui-selected td.filename");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
var result;
result = classElements[x].innerHTML;
$.ajax({
async: true,
type: "DELETE",
method: 'POST',
url: '../public/deletefile',
data: { filename: result, "_token": csrf },
success: function(response) {
$('#results').html(response);
}
});