Answer the question
In order to leave comments, you need to log in
What is the correct way to write an Ajax post deletion script?
Hello.
Wrote a small script that deletes entries from the database. The problem is that when you click the delete button, the first record that is in the database is always deleted, and not the one that is needed. In the url, it seems like I am passing a link to the deletion route and id
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).attr('data-id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deletePost',['id' => $post->id])}}",
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
}
});
return false;
});
});
</script>
Route::delete('/id{id}/delete', '[email protected]')->name('deletePost'); //Удал
public function delete($id) {
$post = Profile::find($id);
$post->delete();
return response()->json([
'message' => 'deleted...'
]);
}
Answer the question
In order to leave comments, you need to log in
OlegGazmanov , The first thing that comes to mind is that your JS code is not written correctly.
Here you click on the entry, if there are many entries on the page, then there cannot be many identical IDs on the page, respectively, all entries must have the .delete class
Second point
Most likely, for each entry in the cycle in the data-id attribute, you assign a real entry ID , for example:
Then in the JS variable var id you save the ID of the post that was clicked, but then:
$("body").on("click","#delete",function(e){
var id = $(this).attr('data-id');
$post->id
url: "{{route('deletePost',['id' => $post->id])}}",
success: function (response){
$("#deletePost").html(response.message);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question