I want to delete records from my table using Ajax and Sweetalert2 dialog. However, when I click the delete button and confirm the delete, the item is deleted from the modal but is still visible in the table. The element only disappears after a manual page refresh.
I already reviewed many questions and videos but I think I'm missing some basic knowledge to identfy my issue..
html
<tbody>
{% if dogs %}
{% for dog in dogs %}
<tr>
<td>{{ dog.dog_name }}</td>
<td>{{ dog.gender }}</td>
<td>{{ dog.breed }}</td>
<td>{{ dog.size }}</td>
<td>{{ dog.dob }} ({{dog.age}} Jahre)</td>
<td>{{ dog.owner }}</td>
<td>{{ dog.created_at }}</td>
<td>{{ dog.updated_at }}</td>
{% if dog.status == "ACTIVE"%}
<td class="text-center">
<span class="badge text-bg-success" style="font-size:0.7em;">{{ dog.status }}</span>
</td>
{% elif service.status == "INACTIVE"%}
<td class="text-center">
<span class="badge text-bg-danger" style="font-size:0.7em;">{{ dog.status }}</span>
</td>
{% endif %}
{% if request.user.is_superuser == True %}
<td class="text-center">
<!--Update-->
<a href="{% url 'dog_record' dog.id %}" class="text-decoration-none">
<button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service">
<i class="bi bi-pencil-fill"></i>
</button>
</a>
<!-- Delete -->
<button type="button" class="btn btn-danger btn-sm DeleteButton" data-url="{% url 'delete_record' dog.id %}">
<i class="bi bi-trash"></i>
</button>
</td>
{% endif %}
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
{% endblock %}
{% block javascripts %}
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<!--Sweet Alert-->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js"></script>
<script>
$(document).ready(function() {
let csrftoken = '{{ csrf_token }}'
$('.DeleteButton').click(function(){
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: $(this).attr('data-url'),
dataType: 'json',
success: (data) => {
console.log("Item deleted");
},
error: (error) => {
console.log(error);
}
});
Swal.fire({
title: "Deleted!",
text: "Your file has been deleted.",
icon: "success"
});
}
});
});
});
</script>
{% endblock javascripts %}
views.py
def delete_record(request, id):
obj = get_object_or_404(Dog, id=id)
if request.method == 'POST':
obj.delete()
return JsonResponse({})
urls.py
path('dog/delete_dog/<int:id>', views.delete_record, name='delete_record'),
I also tried the following function but it didn't change anything.iews.py
#views.py
def delete_record(request, id):
obj = get_object_or_404(Dog, id=id)
if request.method == 'POST':
obj.delete()
return redirect('dogs')
def dogs(request):
dogs = Dog.objects.all()
if request.user.is_authenticated:
return render(request, 'dog/dogs.html', {'dogs':dogs})
else:
return login_user(request)
#urls.py
path('dog/dogs/', views.dogs, name='dogs'),
First you need to assign id to your rows.
{% for dog in dogs %}
<tr id="{{dog.id}}">
<td>{{ dog.dog_name }}</td>
<td>{{ dog.gender }}</td>
Then you can delete the row once ajax call is successful.
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: $(this).attr('data-url'),
dataType: 'json',
success: (data) => {
document.getElementById(this.parent.id).remove()
},
error: (error) => {
console.log(error);
}
});
This will update the table and remove the dom element.
Here is your full updated code.-:
<tbody>
{% if dogs %}
{% for dog in dogs %}
<tr id='{{dog.id}}'>
<td>{{ dog.dog_name }}</td>
<td>{{ dog.gender }}</td>
<td>{{ dog.breed }}</td>
<td>{{ dog.size }}</td>
<td>{{ dog.dob }} ({{dog.age}} Jahre)</td>
<td>{{ dog.owner }}</td>
<td>{{ dog.created_at }}</td>
<td>{{ dog.updated_at }}</td>
{% if dog.status == "ACTIVE"%}
<td class="text-center">
<span class="badge text-bg-success" style="font-
size:0.7em;">{{ dog.status }}</span>
</td>
{% elif service.status == "INACTIVE"%}
<td class="text-center">
<span class="badge text-bg-danger" style="font-
size:0.7em;">{{ dog.status }}</span>
</td>
{% endif %}
{% if request.user.is_superuser == True %}
<td class="text-center">
<!--Update-->
<a href="{% url 'dog_record' dog.id %}" class="text-decoration-none">
<button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service">
<i class="bi bi-pencil-fill"></i>
</button>
</a>
<!-- Delete -->
<button type="button" class="btn btn-danger btn-sm DeleteButton" data-url="{% url 'delete_record' dog.id %}">
<i class="bi bi-trash"></i>
</button>
</td>
{% endif %}
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
{% endblock %}
{% block javascripts %}
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<!--Sweet Alert-->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js"></script>
<script>
$(document).ready(function() {
let csrftoken = '{{ csrf_token }}'
$('.DeleteButton').click(function(){
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: $(this).attr('data-url'),
dataType: 'json',
success: (data) => {
document.getElementById(this.parent.id).remove()
},
error: (error) => {
console.log(error);
}
});
Swal.fire({
title: "Deleted!",
text: "Your file has been deleted.",
icon: "success"
});
}
});
});
});
</script>
{% endblock javascripts %}