This doc is a work in progress…

Using Django version: 1.6.2

Basic Ajax Example

from django.shortcuts import render
def basicajax(request):
    context = {}

    # Draw initial page
    if request.method == 'GET':
        return render(request, 'basic_ajax.html', context)

    # Handle posts
    elif request.method == 'POST':

        # Make sure request is Ajax
        if request.is_ajax():
            context['textbox_data'] = request.POST['textbox']
            context['hiddenfield_data'] = request.POST['hiddenfield']

            # Return response as JSON
            return HttpResponse(json.dumps(context), content_type='application/json')
        # Handle errors here

  • We are returning an HttpResponse, not a render
  • content_type='application/json' is necessary. Otherwise the Ajax success callback returns the data as a string
  • content_type used to be mimetype. Some documentation online still shows up using this but it is now deprecated. Use content_type
  • The data that is passed in from the hidden fields can be used to separate different Ajax requests from the same page. Just give each Ajax form an identifier in a hidden field and use that field to handle the logic in


    <title>Basic Ajax Example</title>
    <script src="//"></script>
    <form id="form_id1">
        <input type="text" name="textbox">
        <input type="submit" value="Search">
        <input type="hidden" name="hiddenfield" value="Cant see me">
        {% csrf_token %}
    Textbox value: <span id="textbox_val"></span>, Hidden field value: <span id="hiddenfield_val"></span>
$(document).ready(function() {
        // Disable submit button

            data: $("#form_id1").serializeArray(), // Easy way to capture all data from form
            success: function(data) {

                // Fill in our output spans

                // Enable submit button
            error: function(xhr, textStatus, errorThrown) {
                alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
        return false; //<---- so page doesn't reload

  • Imports jQuery at the top
  • url="", within the Ajax call to submit to same page
  • To fill the data in the Ajax call use serializeArray(), not serialize()
  • {% csrf_token %} must be present within each form

from django.conf.urls import patterns, include, url
from hellodjango.views import *
urlpatterns = patterns('',
    url(r'^examples/basicajax/', basicajax),

Leave a reply