Getting Started with AJAX in Django: a Simple jQuery Approach

AJAX in Django using jQuery

AJAX in Django using jQuery

I recently created a side project to explore a few tech areas I wanted to learn more thoroughly. One of those areas was how to implement AJAX in Django using jQuery.

In a nutshell, the site, (update 3/5/2013: the site is temporarily offline as switch my Facebook Connect implementation from django-socialregistration to django-social-auth) presents three facts about you and challenges your friends to click on the one that is a lie.

When your friend clicks on a fact, I send the clicked fact_id via AJAX to a url. A Django url pattern routes the click to a view where I check what “type” the fact is, return the result via JSON to the client and update the page dynamically without a page refresh.

Below are the stripped down page, url pattern and view that I use to get this done. You can also check out my simple but working AJAX in Django using jQuery demo page.


[sourcecode language="html"]
I love bugs
I love hugs
I love pugs
Click on the lie!

[sourcecode language="python"] # Process a quiz guess url(r'^test/(?P\d+)/$', quiz_guess, name='quiz_guess'), [/sourcecode]

[sourcecode language="python"] from django.utils import simplejson def quiz_guess(request, fact_id):    message = {"fact_type": "", "fact_note": ""} if request.is_ajax(): fact = get_object_or_404(Fact, id=fact_id) message['fact_type'] = fact.type message['fact_note'] = fact.note else: message = "You're the lying type, I can just tell." json = simplejson.dumps(message) return HttpResponse(json, mimetype='application/json') [/sourcecode]

This, of course, assumes that you have defined a model called “Fact”, that a fact has a “type” and “note” and that you have created the above three facts and they have IDs of 1, 2 and 3. In my real view, I do a few other things like save the click and check whether it is the first one on the quiz.

Also, in the page I do more than update the text of the “result” div. I also update the facepiles of the correct and incorrect guessors, change the percentage who guessed right/wrong and change the background of the clicked fact.

If you want to see AJAX in Django using jQuery as fully implemented, please go ahead and create a sample quiz for yourself by going here and clicking the “Make Your Own Quiz” button.

You will have to connect to the site via Facebook to create a test, but if this makes you uncomfortable, you can connect temporarily, see how it all works and then go to “Facebook > Account > Privacy Settings > Apps and Websites > Edit your settings” and revoke the connection privilege.