views:

65

answers:

2

Is there any way to force an <a href> to do a delete request when clicked instead of a regular GET?

The "Rails" way is to dynamically generate a <form> tag that adds the appropriate params so that it gets routed to the right place, however I'm not too fond of that much DOM manipulation for such a simple task.

I thought about going the route of something like:

$("a.delete").click(function(){
    var do_refresh = false;
    $.ajax({
        type: "DELETE",
         url: "my/path/to/delete",
     success: function(){
                  do_refresh = true;
              },
     failure: function(){
                  alert("There is an error");
              }
    });
    return do_return; //If this is false, no refresh would happen. If it
                      //is true, it will do a page refresh.
});

I'm not sure if the above AJAX stuff will work, as it's just theoretical. Is there any way to go about this?

Note:
Please don't recommend that I use the rails :method => :delete on link_to, as I'm trying to get away from using the rails helpers in many senses as they pollute your DOM with obtrusive javascript. I'd like this solution to be put in an external JS file and be included as needed.

+2  A: 

According to the docs:

http://api.jquery.com/jQuery.ajax/

the DELETE method is allowed but not supported on all browsers, so you should take a look here:

http://stackoverflow.com/questions/165779/are-the-put-delete-head-etc-methods-available-in-most-web-browsers

mamoo
I understand that it is available as AJAX. I was wondering if there was a NON-AJAX way to do a delete request OTHER than wrapping the request in a dynamic form in the same way the rails helpers do.
Mike Trpcic
You can set the method to DELETE, but it will only work on Html5, so it will probably cause you some issues with older browsers.
mamoo
+1  A: 

This is what i do:

$("a.delete").live('click', function() {
        $.post(this.href, "_method=delete", function(data) {
            //do refresh
        });
        return false;
    })

But i don't really know which all browsers support it and which don't. I tested it on mac with Firefox 2 and 3.6, safari 3 and chrome beta 5.0.375.70 and it works.

Shripad K
You set rel=nofollow using jQuery? Just a heads-up: spiders will not run your JS so they're not going to honour that.
Andrew Vit
@Andrew: Thanks a ton! :) I completely forgot that spiders don't parse the JS. Will use in the markup instead.
Shripad K