32 min read

Since our project is a Web 2.0 application, it should be heavily focused on the user experience. The success of our application depends on getting users to post and share content on it. Therefore, the user interface of our application is one of our major concerns. This article will improve the interface of our application by introducing Ajax features, making it more user-friendly and interactive.

Ajax and Its Advantages

Ajax, which stands for Asynchronous JavaScript and XML, consists of the following technologies:

HTML and CSS for structuring and styling information.

and for structuring and styling information. JavaScript for accessing and manipulating information dynamically.

XMLHttpRequest , which is an object provided by modern browsers for exchanging data with the server without reloading the current web page.

, which is an object provided by modern browsers for exchanging data with the server without reloading the current web page. A format for transferring data between the client and server. XML is sometimes used, but it could be HTML , plain text, or a JavaScript-based format called JSON .

Ajax technologies let code on the client-side exchange data with the server behind the scenes, without having to reload the entire page each time the user makes a request. By using Ajax, web developers are able to increase the interactivity and usability of web pages.

Ajax offers the following advantages when implemented in the right places:

Better user experience. With Ajax, the user can do a lot without refreshing the page, which brings web applications closer to regular desktop applications.

Better performance. By exchanging only the required data with the server, Ajax saves bandwidth and increases the application’s speed.

There are numerous examples of web applications that use Ajax. Google Maps and Gmail are perhaps two of the most prominent examples. In fact, these two applications played an important role in spreading the adoption of Ajax, because of the success that they enjoyed. What sets Gmail from other web mail services is its user interface, which enables users to manage their emails interactively without waiting for a page reload after every action. This creates a better user experience and makes Gmail feel like a responsive and feature-rich application rather than a simple web site.

This article explains how to use Ajax with Django so as to make our application more responsive and user friendly. We are going to implement three of the most common Ajax features found in web applications today. But before that, we will learn about the benefits of using an Ajax framework as opposed to working with raw JavaScript functions.

Using an Ajax Framework in Django

In this section we will choose and install an Ajax framework in our application. This step isn’t entirely necessary when using Ajax in Django, but it can greatly simplify working with Ajax. There are many advantages to using an Ajax framework:

JavaScript implementations vary from browser to browser. Some browsers provide more complete and feature-rich implementations, whereas others contain implementations that are incomplete or don’t adhere to standards. Without an Ajax framework, the developer must keep track of browser support for the JavaScript features that they are using, and work around the limitations that are present in some browser implementations of JavaScript. On the other hand, when using an Ajax framework, the framework takes care of this for us; it abstracts access to the JavaScript implementation and deals with the differences and quirks of JavaScript across browsers. This way, we concentrate on developing features instead of worrying about browser differences and limitations.

The standard set of JavaScript functions and classes is a bit lacking for fully fledged web application development. Various common tasks require many lines of code even though they could have been wrapped in simple functions. Therefore, even if you decide not to use an Ajax framework, you will find yourself having to write a library of functions that encapsulates JavaScript facilities and makes them more usable. But why reinvent the wheel when there are many excellent Open Source libraries already available?

Ajax frameworks available on the market today range from comprehensive solutions that provide server-side and client-side components to light-weight client-side libraries that simplify working with JavaScript. Given that we are already using Django on the server-side, we only want a client-side framework. In addition, the framework should be easy to integrate with Django without requiring additional dependencies. And finally, it is preferable to pick a light and fast framework. There are many excellent frameworks that fulfil our requirements, such as Prototype, the Yahoo! UI Library and jQuery. I have worked with them all and they are all great. But for our application, I’m going to pick jQuery, because it’s the lightest of the three. It also enjoys a very active development community and a wide range of plugins. If you already have experience with another framework, you can continue using it during this article. It is true that you will have to adapt the JavaScript code in this article to your framework, but Django code on the server-side will remain the same no matter which framework you choose.

Now that you know the benefits of using an Ajax framework, we will move to installing jQuery into our project.

Downloading and Installing jQuery

One of the advantages of jQuery is that it consists of a single light-weight file. To download it, head to http://jquery.com/ and choose the latest version (1.2.3 at the time of writing). You will find two choices:

Uncompressed version: This is the standard version that I recommend you to use during development. You will get a .js file with the library’s code in it.

Compressed version: You will also get a .js file if you download this version. However, the code will look obfuscated. jQuery developers produce this version by applying many operations on the uncompressed .js file to reduce its size, such as removing white spaces and renaming variables, as well as many other techniques. This version is useful when you deploy your application, because it offers exactly the same features as the uncompressed one, but with a smaller file size.

I recommend the uncompressed version during development because you may want to look into jQuery’s code and see how a particular method works. However, the two versions offer exactly the same set of features, and switching from one to another is just a matter of replacing one file.

Once you have the jquery-xxx.js file (where xxx is the version number), rename it to jquery.js and copy it to the site_media directory of our project (Remember that this directory holds static files which are not Python code). Next, you will have to include this file in the base template of our site. This will make jQuery available to all of our project pages. To do so, open templates/base.html and add the highlighted code to the head section in it:



Django Bookmarks |

{% block title %}{% endblock %}

type="text/css" />







To add your own JavaScript code to an HTML page, you can either put the code in a separate .js file and link it to the HTML page by using the script tag as above, or write the code directly in the body of a script tag:





The first method, however, is recommended over the second one, because it helps keep the source tree organized by putting HTML and JavaScript code in different files. Since we are going to write our own .js files during this article, we need a way to link .js files to templates without having to edit base.html every time. We will do this by creating a template block in the head section of the base.html template. When a particular page wants to include its own JavaScript code, this block may be overridden to add the relevant script tag to the page. We will call this block external, because it is used to link external files to pages. Open templates/base.html and modify its head section as follows:



Django Bookmarks | {% block title %}{% endblock %}

type="text/css"/>



{% block external %}{% endblock %}





And we have finished. From now on, when a view wants to use some JavaScript code, it can link a JavaScript file to its template by overriding the external template block.

Before we start to implement Ajax enhancements in our project, let’s go through a quick introduction to the jQuery framework.

The jQuery JavaScript Framework

jQuery is a library of JavaScript functions that facilitates interacting with HTML documents and manipulating them. The library is designed to reduce the time and effort spent on writing code and achieving cross-browser compatibility, while at the same time taking full advantage of what JavaScript offers to build interactive and responsive web applications.

The general workflow of using jQuery consists of two steps:

Select an HTML element or a group of elements to work on.

Apply a jQuery method to the selected group

Element Selectors

jQuery provides a simple approach to select elements; it works by passing a CSS selector string to a function called $. Here are some examples to illustrate the usage of this function:

If you want to select all anchor ( $(“a”)

If you want to select anchor elements which have the .title CSS class, use $(“a.title”)

CSS class, use To select an element whose ID is #nav , you can use $(“#nav”)

, you can use To select all list item ( ) elements inside #nav , use $(“#nav li”)

elements inside , use

And so on. The $() function constructs and returns a jQuery object. After that, you can call methods on this object to interact with the selected HTML elements.

jQuery Methods

jQuery offers a variety of methods to manipulate HTML documents. You can hide or show elements, attach event handlers to events, modify CSS properties, manipulate the page structure and, most importantly, perform Ajax requests.

Before we go through some of the most important methods, I highly recommend using the Firefox web browser and an extension called Firebug to experiment with jQuery. This extension provides a JavaScript console that is very similar to the interactive Python console. With it, you can enter JavaScript statements and see their output directly without having to create and edit files. To obtain Firebug, go to http://www.getfirebug.com/, and click on the install link. Depending on the security settings of Firefox, you may need to approve the website as a safe source of extensions.

If you do not want to use Firefox for any reason, Firebug’s website offers a “lite” version of the extension for other browsers in the form of a JavaScript file. Download the file to the site_media directory, and then include it in the templates/base.html template as we did with jquery.js:



Django Bookmarks | {% block title %}{% endblock %}

type="text/css"/>





{% block external %}{% endblock %}





To experiment with the methods outlined in this section, launch the development server and navigate to the application’s main page. Open the Firebug console by pressing F12, and try selecting elements and manipulating them.

Hiding and Showing Elements

Let’s start with something simple. To hide an element on the page, call the hide() method on it. To show it again, call the show() method. For example, try this on the navigation menu of your application:

>>> $("#nav").hide()

>>> $("#nav").show()



You can also animate the element while hiding and showing it. Try the fadeOut(), fadeIn(), slideUp() or slideDown() methods to see two of these animated effects.

Of course, these methods (like all other jQuery methods) also work if you select more than one element at once. For example, if you open your user page and enter the following method call into the Firebug console, all of the tags will disappear:

>>> $('.tags').slideUp()



Accessing CSS Properties and HTML Attributes

Next, we will learn how to change CSS properties of elements. jQuery offers a method called css() for performing CSS operations. If you call this method with a CSS property name passed as a string, it returns the value of this property:

>>> $("#nav").css("display")

Result: "block"



If you pass a second argument to this method, it sets the specified CSS property of the selected element to the additional argument: