This is my jquery code
$(document).on('click', '.btnDeleteStudent', function () {
var id = $(this).val();
var token = $("meta[name='csrf-token']").attr("content");
console.log("it Works");
$.ajax({
type: "DELETE",
url: "/delete-student/" id,
dataType: "json",
data: {
"id": id,
"_token": token,
},
success: function (){
console.log("it Works");
}
});
});
Here is my controller
public function destroy($id)
{
Student::find($id)->delete($id);
return response()->json([
'success'=> 'Record deleted successfully'
]);
}
//here is my web.php routing Route::delete('delete-student/{id}', [StudentController::class, 'destroy']);
CodePudding user response:
In your routes/web.php
file. Change what you have from
Route::delete('delete-student/{id}', [StudentController::class, 'destroy']);
TO THIS
Route::post('delete-student/{id}', [StudentController::class, 'destroy'])->name('student.delete');
Change your jQuery code to this:
$(document).on('click', '.btnDeleteStudent', function () {
var id = $(this).val();
var url = "{{ route('student.delete', ':id') }}";
url = url.replace(':id', id);
var token = $("meta[name='csrf-token']").attr("content");
console.log("it Works");
$.ajax({
type: "post",
url: url,
dataType: "json",
data: {'_method':'POST', '_token': token},
success: function (){
console.log("it Works");
}
});
});
This is a better approach and will definitely work.
EXPLANATION : You first assign a name to the route so you can assign the id
parameter to the route()
helper function.
Next, use a POST
route instead of DELETE
, since you are submitting a form via AJAX.
Next, assign the url to a variable in your JavaScript, then pass it to your AJAX request.
That's all!