stephan
stephan

Reputation: 2393

Is jQuery passing the correct variable to my Django view?

I am trying to figure out a way to let the end user delete items for sale (if they are the seller), via AJAX. I'm sure my code below has more than few errors, but my question specifically is with the jQuery AJAX function below.

is 'id' taking the 'entryname' and sending it up to my views? Did I do this correctly?

TEMPLATE.HTML

{% for entry in latest_entries %}
   entry.name <div class="delete_button" id="{{ entry.name }}">delete</div>
   entry.price
   entry.picture
   entry.sellername

{% endfor %}

JQUERY

 <script>
 $(document).ready(function() {
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: "POST",
            url: "/storefront/",
            data: { entryname:id },
            success: function(response){
                alert(response.success);
            }
        });
        return false;
    });
});
</script>

VIEWS.PY

latest_entries=Entry.objects.order_by('-pub_date')[:16]

@login_required
def delete_object(request):
   if request.is_ajax():
      object_name = request.POST.get('entryname')
      Entry.objects.get(id=object_name).delete()
      return HttpResponseRedirect('/storefront/')

Upvotes: 0

Views: 637

Answers (2)

rockingskier
rockingskier

Reputation: 9346

You are saving the id to the variable id

var id = $(this).attr('id');

but you are sending the variable entryname (which does not exist so is undefined)

data: { entryname:entryname },

What you want it:

data: { entryname: id },

Update

You are also missing a "

 entry.name <div class="delete_button" id="{{ entry.name }}">delete</div>

Upvotes: 1

Musa
Musa

Reputation: 97672

You have

data: { entryname:entryname },

but no entryname variable defined. there is an id variable defined. Maybe it should be

data: { entryname:id },

Upvotes: 0

Related Questions