Using PUT and DELETE methods in AJAX requests with prototype.js

Whenerver I write JavaScript I use prototype.js. I find it brilliant, especially when you deal with AJAX. With this library it’s easy to create an AJAX request and process its response from the server.

To send an AJAX request you create a following HTML code:

<a href="#" id="ahref">a link</a>
...
$('ahref').onclick = function() {
    new Ajax.Request('/some_url', {
        method:'get',	
        parameters:'param1=value',
        onSuccess: function(transport){
            var responseXml = transport.responseXML;
            ...
        },
        onFailure:function(){ alert('Something went wrong...') }
    });
    return false;
}

This way, you create a request with GET and POST method. Recently, while developing a SOA system based on REST (REpresenational State Transfer), I faced a problem of creating requests also with other HTTP methods.

In short, REST allows using a few HTTP methods. The most popular are:

  • GET – for obtaining representation of a resource
  • POST – for updating or creating a representation of a resource
  • PUT – for creating a representation of a resource
  • DELETE – for removing a representation of a resource

Again, prototype.js helps a lot. Since version 1.5, it is possible to use all those methods (formerly, it supported only GET and POST). PUT and DELETE methods are realized by tunneling over POST. Also, “_method=METHOD_NAME” is added as a query parameter with the request. The only thing to do is to prepare relevant logic on the server side to manage the request.

Suppose you have a servlet that allows adding a resource to a database and it is invoked with the following URL:
http://example.com/servlet/RESOURCE_URL.

A simplified definition of a Ajax.Request object in prototype would be as follows:

new Ajax.Request('/some_url', {
    method:'put',
    parameters:'url=RESOURCE_URL'
});

In the JavaServlet, you obtain the request and manage it like that:

@Override
protected void doPost(
    HttpServletRequest req, 
    HttpServletResponse res) 
    throws ServletException, IOException {
    if (req.getParameter("_method") != null 
        && "put".equalsIgnoreCase(req.getParameter("_method"))) {
        doPut(req, res);
    }
}

9 Responses to “Using PUT and DELETE methods in AJAX requests with prototype.js”


  • Shouldn’t AJAX Request for adding new resource, identified by RESOURCE_URI, via REST service look like this:

    new Ajax.Request('http://example.com/servlet/RESOURCE_URI', {
    method:'put',
    parameters:''
    });

  • Filip, you’re absolutely right! If you fully support REST, to be more accurate during adding a resource, you must invoke Ajax.Request the manner you exposed.

    However, for this particular example, you can omit “parameter” section. So you can just write:

    
    new Ajax.Request('http://example.com/servlet/RESOURCE_URI',  
    method:'put' });
    

  • Thanx for the tip.
    It helps me a lot.

  • from: http://www.prototypejs.org/assets/2008/1/25/prototype-1.6.0.2.js.
    Looks like they just emulating other methods(except get and post),
    code fragment:
    if (!['get', 'post'].include(this.method)) {
    // simulate other verbs over post
    params['_method'] = this.method;
    this.method = ‘post’;
    }

    still looking for some simple web page for testing REST services…

  • Hello Filip!

    Could you provide some example code for REST service which processes PUT requests. I made it this way but it doesn’t work. Tomcat returns HTTP error 405. (I use FF2.)

    @PUT
    @Path(“/book/{id}”)
    public void updateBook(@PathParam(“id”) Integer id, @QueryParam(“name”) String name) {
    bookMap.put(id,name);
    }

    Thanks.

  • Avramucz,
    Teh example is provided in this post…
    And my name is Jaroslaw ;)

  • A minor remark: REST stands for “REpresentational State Transfer”, not “REpresenational State Browser”.

  • Adomas – ggot point! I’ll change it now :)
    Thanks!

  • There is a detail here that is incorrect. POST is for creating new resources elements and PUT is for creating or updating. The key difference is that PUT should be idempotent while POST is not. So PUTing the same thing twice should not result in a different state, whereas POSTing the same thing may create multiple entries (or it may not, but nothing in the HTTP stack should assume it doesn’t).

Leave a Reply