PUT and DELETE with jQuery

I became a big fan of REST. Especially articles and code by Joe Gregorio, mainly his "How to create a REST Protocol", were a great help to me.

Together with AJAX, it allows me to create clean APIs for my web applications and paves the way for user interfaces with more interaction as they are known from the desktop. It comes with a price tag, of course, and that says "JavaScript dependency".

My first contact with JavaScript was around 1994/1995 together with HTML 3, Netscape 3 and the Web itself, when an issue of the German computer magazine CHIP drew my attention during a summer holiday on some island between Europe and Africa. Although using JavaScript was interesting and added capabilities that at some point seemed essential, browser support was a nightmare regarding pretty much anything back then (and with many years to come). Therefore I started to avoid JavaScript in websites for essential functionality very soon and kept it that way, until I eventually came across jQuery more than ten years later.

Not long ago I haven't been aware of any common JavaScript libraries at all, but with toolkits like Prototype, MooTools, Dojo and others that probably is the way it is done (and necessary) for Web 2.0. Today, developers can assume people have JavaScript support enabled when visiting websites providing features they like. Next to this wide availability and acceptance (although security issues still remain and new ones appeared), things including much improved browser support, libraries' browser abstraction and jQuery's CSS-like selectors brought back the fun to me.

Getting back to REST, one piece (actually two pieces) are missing to close the gap from jQuery to APIs: jQuery still has no support for doing requests using the PUT and DELETE methods of HTTP, for whatever reason.

Here is the code that adds support for them to jQuery and that has served me well so far:

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

It's basically just a copy of $.post() with the method parameter adapted. Hopefully, something like makes it into jQuery soon. And yes, I should probably file a ticket. If you're bound to an older release, this should be helpful, too.

Now have fun with AJAX, REST, and all the other buzzword technologies -- especially if this resolves what kept you from doing so ;)