How to perform an Ajax request in Django

Ajax request are everywhere in modern web applications. No matter which platform you are using for development, the main scheme is always the same. You send a request to a server side method using JavaScript, jQuery etc. and server processes the request, prepares the response and sends this response to client (browser). Finally, response is received and processed by the client-side code (script) and dynamically generated content is displayed to the users.

Flow is the same in Django. So, what we need to implement here?

1- We need a view function to receive and handle the request

2- We need a mapping in urls.py file to map the request url (which will be specified in the requesting client-side jQuery script) to the view function in 1

3- We need the client-side script to make the request to the url in 2 and handle/render the response

Let me clarify by some simple code snippets.

1- Sample view function:

Here we convert the resulting dictionary into a JSON object and return it as an HttpResponse.

2- Sample mapping in urls.py:

3- Sample jQuery script to send the request and get/render the response:

Hope this helps.
Good Luck,
Serdar

Serdar Osman Onur
I love coding web stuff, learning/applying new technologies and techniques to create things on the internet since 2004. AboutMe G+ twitter
Serdar Osman Onur

@serdarosmanonur

hard work, determination, dedication, patience, consistency, faith
"We forge our bodies in the fire of our will" - Enter the Dragon - 1973 - 3 days ago
Serdar Osman Onur