Home > front end >  Delete element with ajax in django
Delete element with ajax in django

Time:09-15

I am currently having some issue in deleting element with ajax in a Django Application. I have some pictures, each of them displayed in a bootstrap card. Basically, my code is kind of working, but I couldn't figure out why, for example, when I display the pictures in the card, in the first one of the list the Delete button doesn't work and, when I have multiple pictures, the delete button works but delete the first picture on the list and not the right one. I may have some mistake in fetching the IDs, but so far I couldn't find where the issue is. I post some code

views.py

def delete_uploaded_picture(request, pk):
picture = Picture.objects.get(id=pk)
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
    picture.delete()
    return JsonResponse({})

js

const deleteForms = document.getElementsByClassName('delete_form')
deleteForms.forEach(deleteForm => deleteForm.addEventListener('click', (e)=>{
e.preventDefault();
let pk = deleteForm.getAttribute('data-pk')
const cardDiv = document.getElementById('card_div' pk)
const clickedBtn = document.getElementById('clicked_btn' pk)
$.ajax({
    type: 'POST', 
    url: $("#my-url-div").data('url'),
    data: {
        'csrfmiddlewaretoken': csrftoken,
        'pk': pk,
    }, 
    success: function(response){
        $('#card_div' pk).hide();
        handleAlerts('success', 'Immagine Rimossa')
    }, 
    error: function(error){
        handleAlerts('danger', 'Ops qualcosa è andato storto!')
    }
})
}))

html

<div >
                    <div >
                    {% if question.picture_set.all %}
                        {% for pic in question.picture_set.all %}
                            <div  id="card_div{{pic.id}}">
                            <form action="" method="post"  data-pk="{{pic.id}}">
                                <div  id="my-url-div" data-url="{% url 'main:delete_uploaded_picture' pk=pic.id %}">
                                    <img  src="{{ pic.picture.url }}" alt="">
                                    <div >
                                        <button type="button"  id="clicked_btn{{pic.id}}">Elimina</button>
                                    </div>
                                </div>
                            </form>
                            </div>
                        {% endfor %}
                    {% endif %}
                    </div>
                </div>

I inspected the html and the IDs are right in the card, so it's something else.

CodePudding user response:

Probably you should change this line:

let pk = deleteForm.getAttribute('data-pk');

To:

let pk = e.currentTarget.getAttribute('data-pk');

Generally in function are you querying objects using className, so it returns multiple object and overrides only one. In e.currentTarget you have element that you clicked, so it does not select it via random way.

Basically I am not sure if the forloop assign is working correctly, the javascript does it own magic in forloops (for example - it makes them asynchrous) so I would not be suprised it does not work as expected and the value you are getting into pk is not that you want.

CodePudding user response:

// Delete Data

$("tbody").on("click", ".btn-del", function () {
    //console.log("Delete Button Clicked");
    let id = $(this).attr("data-sid");
    let csr = $("input[name=csrfmiddlewaretoken").val();
    //console.log(id);
    mydata = { sid: id, csrfmiddlewaretoken: csr };
    mythis = this;
    $.ajax({
        url: "{% url 'delete' %}",
        method: "POST",
        data: mydata,
        success: function (data) {
            //console.log(data);
            if (data.status == 1) {
                $("#msg").text("Data Deleted Successfully");
                $("#msg").show();
                $(mythis).closest("tr").fadeOut();
            }
            if (data.status == 0) {
                $("#msg").text("Unable to Delete Data");
                $("#msg").show();
            }
        },
    });
});

========= Output ==============

enter image description here

  • Related