Ok, now you got dojango and you want to write an AJAX app. There are some basics that just need to be provided in order to make that a piece of cake. Dojango offers them. And this article will show you how to best plug those pieces together and get up and running with ajax and dojango.
This article will show you how to simply pass data properly from the backend to the client.

JSON communication with the server
There are enough use cases (and they are becoming more) when you want to get data from the server and the most common data format nowadays for that is JSON, for various good reasons.
Let’s construct a simple form who’s data we want to submit to the server and know if it all went ok or not. For now we just print the submitted data on the django console (from where you started the local dev server) and we let the user know about the submission with the small text “Submitted” beside the submit button.
So let’s get started with the JavaScript side. Dojango luckily provides us with the basic infrastructure, so let’s create a template that extends dojango/base.html (it is available since the settings.py includes the app “dojango”, see here for instructions), that provides us with everything we need to have dojo running even the doctype of the document and HTML headers, just in short a valid HTML file, we only have to worry about our code.
So let’s build the simple.html file in the templates folder of our django app (I called my app “core”).

{% extends "dojango/base.html" %}

{% block dojango_page_title %}Simple AJAX with dojango{% endblock %}

{% block dojango_header_extra %}
    <script type="text/javascript">
        function userFormSubmit(){
            var form = dojo.byId("userForm");
            dojo.xhrPost({url:form.action,
                handleAs: "json",
                content:{surname:form.surname.value,
                    firstname:form.firstname.value
                },
                load:function(response, ioArgs){
                    dojo.byId("info").innerHTML = "Submitted";
                }
            });
        }
    </script>
{% endblock %}

{% block dojango_content %}
    <form id="userForm" onsubmit="userFormSubmit(); return false;" action="/simple-ajax-set/">
        First name: <input id="firstname" /><br />
        Surname: <input id="surname" /><br />
        <input type="submit" value="Submit" /> <span id="info"></span>
    </form>
{% endblock %}

As you can see we are overriding a couple of blocks, that are defined in the dojango/base.html. The first one (line 3) is just for setting the page title, the second one (line 5) is for putting our JavaScript code inside html-head. And “dojango_content” (line 21) is finally the content of the body node.
We also have to wire up the template to render when we access http://localhost:8000/simple/ and the AJAX method, that we submit the data to, like so in the urls.py:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^dojango/', include('dojango.urls')),
   
    (r'^simple/', 'core.views.simple'),
    (r'^simple-ajax-set/', 'core.views.simple_ajax_set'),
)

We just added the two last lines that map our URLs (line 6 and 7) to the view functions.
Our views.py just needs to implement these two functions, like this.

from django.shortcuts import render_to_response
from dojango.decorators import json_response

def simple(request):
    return render_to_response('simple.html')

@json_response
def simple_ajax_set(request):
    firstname = request.POST['firstname']
    surname = request.POST['surname']
    print firstname, surname
    return {'success':True}

The function “simple” (line 4) uses the standard django way to render a view and return the content to the client. It finds the template simple.html in the app’s template path.
The function “simple_ajax_set” (line 8) will receive our form data and (for now) only print them. You can see the first speciality here, it uses the decorator “json_response” that we imported from dojango.decorators. This decorator takes care of returning proper JSON data, all the data you stuff in there are returned to the client JSON encoded, it basically is json_encode as described here. If you have AJAX calls and want to return JSON data, this is the easiest way to do it and it comes with dojango. It is a special (though very simple) implementation that has not made it’s way into the django core because it is really just AJAX-focused, while the django serializer is django model focused. Additionally this implementation solves a couple of problems and adds some features that are very useful when working with AJAX data, for more explainations see this article.

Handle the return
Now we can submit the form and see that the data got submitted. We don’t know yet if the data had been successfully handled on the server. So let’s add proper error handling.

function userFormSubmit(){
    var form = dojo.byId("userForm");
    dojo.xhrPost({url:form.action,
        handleAs:"json",
        content:{surname:form.surname.value,
            firstname:form.firstname.value
        },
        load:function(response, ioArgs){
            if (response.success){
                dojo.byId("info").innerHTML = "Submitted successfully";
            } else {
                dojo.byId("info").innerHTML = "Error: "+response.error;
            }
        },
        error:function(data){ // This happens on a 500 error or alikes.
            dojo.byId("info").innerHTML = "Error sending data.";
        }
    });
}

If you looked into the return data (i.e. via FireBug) you might have seen that

{"success":true}

was returned. But until now this was passed into the load function (line 8) as a string, but we want them as JSON. So we have to tell the xhrPost() call to handle it as JSON (line 4). Now we can also evaluate the success value easily as shown in line 9. If the server returns

success

with the value

false

we know something went wrong on the server. Let’s implement on the server that the surname has to have at least three characters. In the case of an error the server returns the additional property “error” which we then show to the user (line 12) to inform him about the error.
The function in line 15 handles all kind of connection and/or submission errors that may occur in a lower level. Make sure to not leave your users in the dark about this.
Let’s look at the server code for that:

@expect_post_request
@json_response
def simple_ajax_set(request):
    ret = {}
    firstname = request.POST['firstname']
    surname = request.POST['surname']
    if len(surname)<3:
        ret['error'] = 'Surname is too short.'
        ret['success'] = False
    if ret['success']:
        # Store the data here
        pass
    return ret

We extended the function a little bit to do some simple error checking. You can see that we add the key “error” to the ret dict, which is then passed to the client if the surname was shorter than three characters. The JSON string returned in this case is

{"success": false, "error": "Surname is too short."}

.
Note that we didn’t explicitly set the value for

success

to

True

, the decorator

json_response

handles that for us. If no exception is thrown it assumes that the function went ok and it can return

success=True

. This comes in very handy, especially when you just have simple one task AJAX functions that i.e. just delete an item, you don’t have to return explicitly that the deletion went well,

json_response

does that for you if you throw no exception. We just made it the default behavior since it was right for most of our use cases.