How do I use AJAX along side Django ?

Introduction

Within this example we will show you a simple example of how to integrate AJAX with Django.

AJAX (Asynchronous JavaScript and XML) is a technique that provides the ability to update parts of a web page, without reloading the whole page. Now days,  typically JSON is the preferred method over XML due to JSON`s lightweight nature (i.e there is no requirement for closing tags like XML).

Example

This example will be built around showing you a simple Django app that uses a simple form of AJAX.

In this example the Django app will take a domain name, submit this to the server via a POST using AJAX. The server will then look up the IP address of the domain name and provide an AJAX based response back to the client.

Below shows you an overview of the process involved.

 

Django app - AJAX

 

Lets step through the process step by step,

  1. Client side :The client issues a HTTP GET for the url /ajaxexample. This is served by the view named ‘main’ and the ‘ajaxexample.html’ template is presented.
  2. Client side : The client then enters a value within the form. The form has an id of #forminput.
  3. Client side : The value from #forminput is this assigned to the variable ‘input_string’ using jquery.
  4. Client side : Once the form is submitted a POST is sent to the URL /ajaxexample_json containing the key pair {input_string : <VALUE >}.
  5. Server side : The view named ‘ajax’ then performs the necessary work on the value (in this case resolving the IP address).
  6. Server side : The view named ‘ajax’ then responds with the new value using the key pair {‘server_response’: <VALUE>}.
  7. Client side : The template (via the use of jquery) then assigns server_response value to the id ‘#result’.

With all that said and done. Here is the config.

Template – ajaxexample.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#button").click(function() {
                    var input_string = $("#forminput").val();
                    $.ajax({
                        url : "/ajaxexample_json", 
                        type : "POST",
                        dataType: "json", 
                        data : {
                            client_response : input_string,
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                        success : function(json) {
                            $('#result').append( 'ServerResponse:' + json.server_response);
                        },
                        error : function(xhr,errmsg,err) {
                            alert(xhr.status + ": " + xhr.responseText);
                        }
                    });
                    return false;
            });
        });
</script>
<form method="post" name="example form" >
        {% csrf_token %}
        <input name="example" id="forminput" type="text">
        <input id="button" type="button" value="send to server"></input>
</form>
<div id="result">
</div>
</body>
</html>

View

from django.http import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
import socket

def main(request):
   return render_to_response('ajaxexample.html', context_instance=RequestContext(request))

def ajax(request):
   if request.POST.has_key('client_response'):
        x = request.POST['client_response']                  
        y = socket.gethostbyname(x)                           
        response_dict = {}                                          
        response_dict.update({'server_response': y })                                                                   
        return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript') 
   else:
        return render_to_response('ajaxexample.html', context_instance=RequestContext(request)

URLConf

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('',
    url(r'^ajaxexample$', 'digajax.views.main'),
    url(r'^ajaxexample_json$', 'digajax.views.ajax'),
)
Rick Donato

Want to become a Django expert?

Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial