A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Django and jQuery AJAX

This is probably my first post for Django. I have only been using it for a few weeks and I am already falling in love with it.

Here is how to do an AJAX “save” using jQuery and Django.

My Javascript would look something like this:

$(document).ready(function() {
        if(save_data()) {
        } else {
    function save_data() {
        $.post("/business/add/", { 
            csrfmiddlewaretoken: $("input[name='id_csrfmiddlewaretoken").val(),
            name: $("#id_name").val(),
            website: $("#id_website").val()
        function(data) {
                UPDATE: You do not need this line if you have "json" as the 3rd parameter for $.post()
                data = json_parse(data); 
                //You must get this file: http://www.JSON.org/json_parse.js
                if(data.status=="success") {
                    return true;
                } else {
                    console.log("status: "+data.status)
                    console.log("error: "+data.error)
                    console.log("POST DATA: "+data.data)
                    $.each(data.data, function(i, n){
                        console.log(">"+i+": "+n);
                    return false;

And my views.py is like this:

def business_add(request):
    success = False
    error = None
    if request.method == 'POST':
        business_form       = BusinessForm(request.POST)
        if (business_form.is_valid()):
            business_name   = business_form.cleaned_data['name']
            business_website  = business_form.cleaned_data['website']
                business = Business(name=business_name,website=business_website)
            except IntegrityError, e:
                success = False
                error = e
                success = True
        business_form   = BusinessForm()
    data = {
        "business_form": business_form,
        "success": success,
        "error": error
        if request.is_ajax():
            results = {"status":"success", "message":"Business saved."}
            data = json.dumps(results)
            return HttpResponse(data)
            return render_to_response("business/business_add.html",
                              data, context_instance=RequestContext(request))
        if request.is_ajax():
            data = json.dumps({"status":"failed", "error":error, "data":request.POST})
            return HttpResponse(data)
            return render_to_response("business/business_add.html",
                              data, context_instance=RequestContext(request))

And last but not the least, my template file:

More HTML here...
<div id="add_business_container" title="Add a business">
    <form id="add_business_form">
        {% csrf_token %}
        <h2>Business info</h2>
        {{ business_form.as_p }}
        <input id="save_button" class="submit" type="submit" value="SAVE"/>
More HTML here...

It is basically just like doing it in any web framework (Zend Framework). But with Django, everything is so easy to understand — you have built-in methods like request.is_ajax()

This entry was posted in General and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>