0

Don't know if this is possible or not. But I'm trying to make it so when a user clicks save or delete anchor, it doesn't redirect anywhere. I guess what I'm asking is, is it possible for a hidden input to recognize the anchor as if it were an input and send it to the view?

Example: Template: * Updated !

<a class="delete" href="javascript:void(0)">delete</a>

Django View: (what I started with)

@login_required
def edit_box(request):
    if 'edit' in request.POST:
         deletes = [int(item) for item in request.POST.getlist('delete')]
         yadda yadda delete code
         ...
    return render_to_response('cart/boxcart.html', context, context_instance=RequestContext(request))

Django View: *Updated !

@login_required
def edit_box(request):
    profile = get_object_or_404(Profile, user=request.user)
    item_in_profile = Item.objects.filter(profile=profile)
    deletes = [int(item_in_profile) for item_in_profile in request.POST.getlist('delete')]
    item_in_profile.filter(id__in=deletes).delete()
    item_in_profile.save()
    return render_to_response('cart/boxcart.html', context, context_instance=RequestContext(request))

ajax attempt:

 $(".delete").click(
      function(){ 
           $.ajax({
                type: "GET",
            url: "/profile/delete/{{ item???}}/",
            dataType: "json",
            success: function(data){
           $("{{ item }}").fadeOut(300, function() { $("{{ item }}").remove() });                       
           }
      });
 });

Or am I going about this all wrong?

Modelesq
  • 5,192
  • 20
  • 61
  • 88

1 Answers1

1

Sure! You don't even need to use a hidden input.

You can make sure that an anchor tag doesn't go anywhere by adding

href="javascript:void(0)"

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

ADditionally, you would need to do some light javascript work.

This will include:

1) adding an onclick event to the anchor

2) when the anchor is clicked get the associated item.id

3) get the action you want to perform ie. save or delete

4) make an ajax request to your django app with the item.id and the action.

5) do something with the response!

This allows the user to perform actions without relying on page refreshes. Ajax is a crucial concept and will be well worth the effort of learning. http://www.w3schools.com/ajax/default.asp

Watch out for posting data through ajax with csrf middleware. It CAN get tricky. https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145