Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Getting Started with AJAX in Django: a Simple jQuery Approach

Image may be NSFW.
Clik here to view.
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, TruthTruthLie.me (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.

ajax_in_django.html:

<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
  $(document).ready(function() {
    $('.fact').bind('click', function () {
      $.get("/test/"+this.id+"/", function(data) {
        if (data.fact_type=="T") {
          guess_result="This fact is true! " + data.fact_note;
        } else {
          guess_result="This fact is false! " + data.fact_note;
        }
        $('#result')[0].innerHTML=guess_result;
      });
   });
});
</script>
</head>
<body>
  <div id="1" class="fact">I love bugs</div>
  <div id="2" class="fact">I love hugs</div>
  <div id="3" class="fact">I love pugs</div>
  <div id="result">Click on the lie!</div>
</body>
</html>

url.py:

# Process a quiz guess
  url(r'^test/(?P<fact_id>\d+)/$',
      quiz_guess,
      name='quiz_guess'),

views.py:

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')

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.


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles