Using jQuery Ajax for Django form submission

I’ve spent some time with Django, a really cool python-based web framework. It’s similar to Rails in that it’s easy to get something up and running quickly, but I find it a little easier to understand, and a little less “black-box” as well. Before the flame wars begin, this is just my opinion and, well, I like Rails as well, simply because I love Ruby’s elegance.

Anyway, I figured out how to do Ajax form submissions so I thought I’d post a little tutorial. This uses jQuery for our javascript/ajax.

First, the template form, which we’ll call search_form.html. It’s pretty basic; it just contains one field to search a data store, as well as a div below the form to be swapped out via our ajax call.

<form action="." method="get">
    <input id="query" type="text" />
    <input id="search-submit" type="submit" value="Search" />    
<div id="search-results">
    {% if show_results %}
        {% include 'song_list.html' %}
    {% endif %}

Nothing really unusual here. We’ve got a Django tag inside the div to conditionally include our search result page based on the presence of a show_results flag, which is shown here as song_list.html:

{% if songs %}
    <ul class="songs">
        {% for song in songs %}
	        {{ song.title }}
	{% endfor %}
{% else %}
    <p>No songs found.</p>
{% endif %}

If we have results, we show them in a list, otherwise we show a message indicating no results.

Next, we have our view in, called search:

def search(request):
	# Holds the songs we will display in the search results:
	songs = []
	# Whether we show results
	show_results = False
	# Holds the query
	q = ""
	# Check both that 'q' exists in request.GET and it's a non-empty value:
	if 'query' in request.GET:
		# Get the query string variable named 'q'
		q = request.GET['query'].strip()
		show_results = True
		songs = Song.objects.filter(title__icontains=q)
	variables = RequestContext(request,
		'songs' : songs,
		'show_results' : show_results,
		'query' : q,
		return render_to_response('song_list.html', variables)
	return render_to_response('search_form.html', variables)

Basically, if the query is legit, it sets the show_results flag to TRUE, it queries the database for songs matching the query, and sets up a response. Notice that in setting up the response it checks for the presence of a request parameter called ajax. This will be set by our javascript, below. This is for graceful degradation–if the user does not have javascript enabled, she will still at least be able to see results with a normal page reload.

And finally, here is the javascript that is on our search_form.html for simplicity. It assumes you have jQuery successfully installed in site_media in your project:

<script type="text/javascript">
$("#search-submit").click(function() {
function search_submit() {
	// Get the query string from the text field
	var query = $("#query").val();
	// Retrieve a page from the server and insert its contents
	// into the selected document.
		"/search/?ajax&query=" + encodeURIComponent(query)
	return false;

The search_submit function gets the value of the element with an id of query (our input field), and loads an element with the id of search-results (our div) with the results from the jQuery ajax method load(). Notice it sets the request parameter ajax for our view to use. This function is called via a click handler on the submit button. And that’s all there is to it! Easy, eh?


About buffalobillion

Web Developer, JavaScript Balrog, Java dude, Ruby/Rails enthusiast. Guitar Playa.
This entry was posted in Web Dev. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s