This doc is a work in progress…
Using Django version: 1.6.2
Basic Ajax Example
views.py
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')
else:
# Handle errors here
pass
Notes
- 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 views.py
basic_ajax.html
<html>
<head>
<title>Basic Ajax Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>
<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 %}
</form>
Textbox value: <span id="textbox_val"></span>, Hidden field value: <span id="hiddenfield_val"></span>
</body>
<script>
$(document).ready(function() {
$("#form_id1").submit(function(event){
// Disable submit button
$("#form_id1").find('input[type=submit]').prop("disabled",true);
$.ajax({
type:"POST",
url:"",
data: $("#form_id1").serializeArray(), // Easy way to capture all data from form
success: function(data) {
// Fill in our output spans
$("span#textbox_val").html(data['textbox_data']);
$("span#hiddenfield_val").html(data['hiddenfield_data']);
// Enable submit button
$("#form_id1").find('input[type=submit]').prop("disabled",false);
},
error: function(xhr, textStatus, errorThrown) {
alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
}
});
return false; //<---- so page doesn't reload
});
});</script>
</html>
Notes
- 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()
, notserialize()
{% csrf_token %}
must be present within each form
urls.py
from django.conf.urls import patterns, include, url
from hellodjango.views import *
urlpatterns = patterns('',
url(r'^examples/basicajax/', basicajax),
)