Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a DELETE request from <a> tag without constructing forms?

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_refresh; //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.

like image 796
Mike Trpcic Avatar asked Jun 24 '26 16:06

Mike Trpcic


2 Answers

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:

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

like image 174
mamoo Avatar answered Jun 27 '26 11:06

mamoo


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.

like image 34
Shripad Krishna Avatar answered Jun 27 '26 12:06

Shripad Krishna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!