Mike Trpcic
Mike Trpcic

Reputation: 25649

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.

Upvotes: 3

Views: 6376

Answers (3)

Khaled Al-Ansari
Khaled Al-Ansari

Reputation: 3970

You can use RESTInTag plugin, it will do the ajax requests for you all you have to do is add a couple of extra attributes to your HTML tag

Example:

HTML

<button class="delete" data-target="my/path/to/delete" data-method="DELETE" data-disabled="true">Delete Article</button>

JavaScript

$(".delete").restintag(optionsObj, function() {
    do_refresh = true
},
function() {
    alert("some error happened");
});

Upvotes: 1

Shripad Krishna
Shripad Krishna

Reputation: 10498

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.

Upvotes: 1

mamoo
mamoo

Reputation: 8166

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?

Upvotes: 2

Related Questions