Answer the question
In order to leave comments, you need to log in
Why is the record not being deleted from the database with Ajax?
I have a script that removes posts from the database. The script basically works, but when you click on the delete button, only the last entry is deleted from the page, and the one I want to delete does not disappear. After reloading the page, everything is fine, which I deleted, disappeared, and the top one, which was deleted, appeared again.
<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).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
$("#textpostdata").remove();
},
});
});
});
</script>
<div class="infinite-scroll" id="textpost">
@foreach($posts as $post)
<div class="list-group-item py-5 textpost" id="textpostdata" data-id="{{$post->id}}">
<div class="media">
<div class="img-post" style="background-image: url({{$user->avatar ?? asset('img/default-ava.jpg')}});"></div>
<div class="media-body">
<div class="media-heading"><small class="float-right text-muted">{{$post->created_at->diffForHumans()}}</small>
<h5>{{$user->name}}</h5>
</div>
@if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
@endif
<br>
@if($post->message)
<div class="text-muted text-small">{!!$post->message!!}</div>
@endif
</div>
</div>
@if(Auth::check())
@if(Auth::user()->id == $user->id)
<div class="text-right">
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
@csrf @method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
</form>
</div>
@endif
@endif
</div>
@endforeach
{{$posts->links()}}
</div>
Route::delete('/post/delete/{id}', '[email protected]')->name('delMusicComment');
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question