Toast Driven

← Back to March 28, 2008

Would You Like Ajax With That?

A variant of a patch I proposed was added to Django's trunk as of a week ago (r7334). It adds a method to all requests that allow you to check if the request was made via an Ajax call or a vanilla GET by a browser. A sample of usage might look like:

def my_friends(request):
    friends = Friend.objects.all()

    if request.is_ajax():
        return render_to_response('friends/list_fragment.html', {'friends': friends})
        return render_to_response('friends/list.html', {'friends': friends})

There is one caveat to this, which is that your Javascript must send an appropriate header with the request that identifies it as an Ajax request. The good news is that all the major Javascript libraries (jQuery, Prototype, YUI, MooTools, Dojo and others) all already send this header automatically. If not, it's easy to add to your own Javascript code (one line).

Simple as it is, it's a patch that's already been very useful to me and hopefully will be to others as well.

Pixel Toast