0

hello I want to delete a Django object using AJAX or JavaScript with confirm message on clicking delete but I don't know how to complete AJAX request.

views.py

def delete(request,id):
    try:
        inta = work.objects.get(pk=id)
        inta.delete()
    except:
        pass
    return HttpResponseRedirect(reverse('home'))

urls.py

url(r'^delete/(?P<id>\d+)/$',views.delete, name='delete')

html :

{& for app in apps &}
<p>{{ app.item0 }}</p>
<p>{{ app.item1 }}</p>
<p>{{ app.item2 }}</p>
<button  data-object-id="{{ app.id }}">remove</button>
{% endfor %}

$('button').on('click', function(){
    var confirmation = confirm("are you sure you want to remove the item?");
    if (confirmation) {
     // execute ajax
        alert('removed');
    }
})
0

2 Answers 2

3

There is more convinient way to write AJAX code:

$('button').on('click', function(){
    let confirmation = confirm("are you sure you want to remove the item?");
    if (confirmation) {
        let object_id = $(this).attr('data-object-id');
        let url = `delete/${object_id}/`;
        $.ajax({
           url: "example.html/my/example",
           data: {
               'csrfmiddlewaretoken': "{{ csrf_token }}"
           },
           type: "DELETE",
           dataType: "json"
         }).done(
              function(){alert("Deleted");}
            ).fail(
              function(){alert("Error");}
            ) 
       });
    }
})
Sign up to request clarification or add additional context in comments.

3 Comments

I get this error Forbidden (CSRF token missing or incorrect.):
I forgot about csrf token in data. Now it should work ;)
I change some lines in your code and now if I try to delete some itam then I take fail (alert error) but the item delete it and I can see that only if I refresh the page here the snippet: var object_id = $(this).attr('data-object-id'); console.log(object_id); //var url = 'delete/${object_id}/'; $.ajax({ url: 'delete/'+object_id+'/', data: { }, beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
0

Assuming that

  • The delete view excepts a DELETE request
  • The javascript code is contained in the HTML


$('button').on('click', function(){
    let confirmation = confirm("are you sure you want to remove the item?");
    if (confirmation) {
        let object_id = $(this).attr('data-object-id');
        let url = `delete/${object_id}/`;
        $.delete(url, {csrfmiddlewaretoken: '{{ csrf_token }}'}, function(){
                alert('removed');
        })
    }
})

If the javascript code is in a separate file you will have to find another way to get the csrf-token, perhaps from a hidden input somewhere on the page.

5 Comments

but I need first to agree to confirm message before delete object some like this ` var confirmation = confirm("are you sure you want to remove the item?"); ` I am confused now
The code you posted already handles the confirmation... Anyway I updated the answer to make it clearer
I try to test it now but don't work if I put code in <script></script> then show me error in ` let` I thing because have red line.
@Mar You are probably using an older version of JS. Try to replace all let with var
I take now error : (index):679 Uncaught TypeError: $.delete is not a function at HTMLButtonElement.<anonymous> ((index):679) at HTMLButtonElement.dispatch (jquery-1.12.4.min.js:3) at HTMLButtonElement.r.handle (jquery-1.12.4.min.js:3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.