django, ajax, and jquery February 09, 2008
Django, ajax, and jQuery can be used to create rich, responsive "single page applications".
I've been playing around with the thought of "single page applications", where a web application will only load an entire page once. Every link click and form submit will then trigger an Ajax event, loading new data to the page.
the django model
Let's start with something familiar, a Django model. Inside your models.py, we'll make an Article model for some blog module:
from django.db import models
class Article(models.Model):
title = models.CharField(maxlength=255)
summary = models.TextField()
body = models.TextField()
For this example, we'll start simple and only use three fields which are all just standard text. When exchanging data back and forth between Javascript and a Django application, you'll want to normalize your data. That means, if you have a DateField, make sure both your client side and server side use the same format ("yyyy-mm-dd").
the django view
Now let's go ahead and create a view where articles can be created:
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from models import Article
@require_http_methods(["POST"])
def article_create(request):
"""Creates a new Article, expects request.POST to have these keys: title, summary, body"""
title, summary, body = request.POST['title'], request.POST['summary'], request.POST['body']
article = Article(title=title, summary=summary, body=body)
article.save() # you'll want to do error checking of course
return HttpResponse("{'success': 'Article was saved'}", mimetype="application/json")
That last line sends back some JSON for our client side Javascript to parse. For our form, we just need to grab the values of each input and send the data to the server. This is dead simple with jQuery.
the jquery code
If our above view had the url "/articles/create/", this would be our Javascript:
// For our article form
$('#article_form').submit(function(event){
event.preventDefault(); // stop the form from submitting and refreshing the page
var form = this; // in jQuery, this refers to the current element, which is #article_form
// grab each form value
var data = {};
data.title = $(form).find('input[@name=title]').val();
data.summary = $(form).find('textarea[@name=summary]').val();
data.body = $(form).find('textarea[@name=body]').val();
// now send the data to the server via AJAX
$.post("/articles/create", data, function(responseData){
// do a simple alert for now, alert "Article was saved"
alert(responseData.success);
}, "json");
});
This Javascript code first finds the form and get the values of each input and textarea elements using val(). It then submits the data to the server using jQuery's $.post() method.
sending data is simple
That's it for sending data to the server using Django, ajax, and jQuery. In the next article, I'll show you how to receive data, parse it, and display something useful to the user (like inserting the article directly on the user's page) besides an alert box.
VinÃcius 04/07/08 09:02:06 PM #1
Hello Hugh, thanks for your tutorial. I tried something based on your example but HttpResponse only prints my response in plain text. Do you known what can be?
Hugh Bien 04/10/08 12:10:23 AM #2
It sounds like the Javascript code isn't registering. Make sure your form has an id of 'article_form'. I would also try sticking a call to
alert()to make sure it's working.kenneth gonsalves 04/18/08 07:18:56 AM #3
nice - when is the next article coming out?