[Fixed]-Pass information from javascript to django app and back

30👍

You’re talking about AJAX. AJAX always requires 3 pieces (technically, just two: Javascript does double-duty).

  1. Client (Javascript in this case) makes request
  2. Server (Django view in this case) handles request and returns response
  3. Client (again, Javascript) receives response and does something with it

You haven’t specified a preferred framework, but you’d be insane to do AJAX without a Javascript framework of some sort, so I’m going to pick jQuery for you. The code can pretty easily be adapted to any Javascript framework:

$.getJSON('/url/to/ajax/view/', {foo: 'bar'}, function(data, jqXHR){
    // do something with response
});

I’m using $.getJSON, which is a jQuery convenience method that sends a GET request to a URL and automatically parses the response as JSON, turning it into a Javascript object passed as data here. The first parameter is the URL the request will be sent to (more on that in a bit), the second parameter is a Javascript object containing data that should be sent along with the request (it can be omitted if you don’t need to send any data), and the third parameter is a callback function to handle the response from the server on success. So this simple bit of code covers parts 1 and 3 listed above.

The next part is your handler, which will of course in this case be a Django view. The only requirement for the view is that it must return a JSON response:

from django.utils import simplejson

def my_ajax_view(request):
    # do something
    return HttpResponse(simplejson.dumps(some_data), mimetype='application/json')

Note that this view doesn’t take any arguments other than the required request. This is a bit of a philosophical choice. IMHO, in true REST fashion, data should be passed with the request, not in the URL, but others can and do disagree. The ultimate choice is up to you.

Also, note that here I’ve used Django’s simplejson library which is optimal for common Python data structures (lists, dicts, etc.). If you want to return a Django model instance or a queryset, you should use the serializers library instead.

from django.core import serializers
...
data = serializers.serialize('json', some_instance_or_queryset)
return HttpResponse(data, mimetype='application/json')

Now that you have a view, all you need to do is wire it up into Django’s urlpatterns so Django will know how to route the request.

urlpatterns += patterns('',
    (r'^/url/to/ajax/view/$', 'myapp.views.my_ajax_view'),
)

This is where that philosophical difference comes in. If you choose to pass data through the URL itself, you’ll need to capture it in the urlpattern:

(r'^/url/to/ajax/view/(?P<some_data>[\w-]+)/$, 'myapp.views.my_ajax_view'),

Then, modify your view to accept it as an argument:

def my_ajax_view(request, some_data):

And finally, modify the Javascript AJAX method to include it in the URL:

$.getJSON('/url/to/ajax/view/'+some_data+'/', function(data, jqXHR){

If you go the route of passing the data with the request, then you need to take care to retreive it properly in the view:

def my_ajax_view(request):
    some_data = request.GET.get('some_data')
    if some_data is None:
        return HttpResponseBadRequest()

That should give you enough to take on just about any AJAX functionality with Django. Anything else is all about how your view retrieves the data (creates it manually, queries the database, etc.) and how your Javascript callback method handles the JSON response. A few tips on that:

  1. The data object will generally be a list, even if only one item is included. If you know there’s only one item, you can just use data[0]. Otherwise, use a for loop to access each item:

    form (var i=0; i<data.length; i++) {
        // do something with data[i]
    }
    
  2. If data or data[i] is an object (AKA dictionary, hash, keyed-array, etc.), you can access the values for the keys by treating the keys as attributes, i.e.:

    data[i].some_key
    
  3. When dealing with JSON responses and AJAX in general, it’s usually best to try it directly in a browser first so you can view the exact response and/or verify the structure of the response. To view JSON responses in your browser, you’ll most likely need an exstention. JSONView (available for both Firefox and Chrome) will enable it to understand JSON and display it like a webpage. If the request is a GET, you can pass data to the URL in normal GET fashion using a querystring, i.e. http://mydomain.com/url/to/ajax/view/?some_data=foo. If it’s a POST, you’ll need some sort of REST test client. RESTClient is a good addon for Firefox. For Chrome you can try Postman. These are also great for learning 3rd-party APIs from Twitter, Facebook, etc.

1👍

Yes, it is possible. If you pass the id as a parameter to the view you will use inside your app, like:
def example_view (request,id)
and in urls.py, you can use something like this:
url(r'^example_view/(?P<id>\d+)/', 'App.views.example_view').

The id in the url /example_view_template/8 will get access to the result using the id which is related to the number 8. Like the 8th record of a specific table in your database, for example.

0👍

About how to capture info from ajax request/urls, Usually you can do that as in a normal django requests, check url dispatcher docs and read about django views from official docs.

About how to return response, just capture the parameters, process your request then give your response with appropriate mimitype.

Sometimes you have to serialize or convert your data to another format like json which can be processed more efficiently in a client-side/js

Leave a comment