Setting up a simple Ajax on Django 1.1 with jQuery can be done fairly quickly if you follow some basic tips.
- Reference the correct IDs.
- Know the correct path base that you're working from.
- Ensure the data is what you expect and return sufficient error information when something isn't right.
The URL
Firstly, set up your Ajax post handler URL. This will be your entry point to the request.
This part sets up the path to your app from your project. For example, we'll make example app. In your "urls.py" file, add the following URL pattern.
urlpatterns = patterns('',
url(r'^example/', include('example_app.urls')),
)
Now, within your example app "urls.py" file, add the pattern for your post handler.
urlpatterns = patterns('',
url(r'^post$', 'example_app.views.ajax_post', name="example_ajax_post"),
)
And there you have it, now you've got a URL for http://yoursite.com/example/post
The handler
Now we actually need that url to handle the request. Create a new function called "ajax_post", or something that matches "example_app.views.ajax_post".
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
from django.utils import simplejson
def example_ajax_post(request):
"""
Just an example handler for the Ajax request.
"""
# Check if the information was posted.
if not request.method == 'POST':
raise Http404
data = { 'error': True, 'message': '' };
int_a = int(request.POST.get("field_a"))
int_b = int(request.POST.get("field_b"))
string_c = request.POST.get("field_c")
## Just some dummy code
# object = get_object_or_404(YourObjectClass, id = int_a)
if int_a < 0 or int_b < 0:
data['message'] = 'No negative numbers allowed.'
data['answer'] = 0
else:
data['error'] = False
data['message'] = 'Request OK!'
data['answer'] = int_a + int_b
data = simplejson.dumps(data)
return HttpResponse(data, mimetype="application/javascript")
Now you have a working handler that spits out JSON output. Example below.
{ 'error': 0, 'answer': 3, 'message': 'Request OK!' }
Also, if you wish to ensure that only logged in users can access this handler, it is easier to add in the following decorator than implement a check.
@login_required
def flag_inappropriate_ajax(request):
The Request
The last step is to make the request using JQuery.
<script type="text/javascript" charset="utf-8">
function example_post(field_a_value, field_b_value, field_c_value) {
callback = function(data, status) {
// If there were no errors, fill the field with the answer.
if (!data.error) {
$('#example_item_message').replaceWith("The answer is: " + data.answer);
}
alert(data.message);
};
// Note: the post url is relative to the URL of the current page
$.post('/example/post', { 'field_a': field_a_value, 'field_b': field_b_value, 'field_c': field_c_value }, callback, 'json');
}
</script>
This script will send a post request to "/example/post" with the given values.
The callback handles the response from JSON output from the post page. Data contains the JSON information already converted into a Javascript object.
[ Source ]