Murtaza Pitalwala
Murtaza Pitalwala

Reputation: 899

How to get values from the Ajax() into Django template?

I have a Django template where it shows multiple values received from the database and passes it to the template, something like following:

in views.py

def test1(requests):
  requests.get...
  requests.get...
  requests.get...
  someQuery = "select id from table;"
  executeQ(someQuery)
  someQuery = "select id from table;"
  executeQ(someQuery)
  someQuery = "select id from table;"
  executeQ(someQuery)
  context = Data1, Data2, Data3
  return render_to_response('test1/index.html', context)

in template/test1/index.html

<html>
  ...... 

<table>
<th> header1 </th>
<th> header2 </th>
<th> header3 </th>

{% for row in context %}
 <td> row.1 </td>   
 <td> row.2 </td>
 <td> row.3 </td>
{% endfor %}

Now, what I want is to update those row.1, row.2, row.3 via Ajax without realoding the page everytime. The data come from the database. So where and how can I put in some Ajax() so this happens with Django?

Upvotes: 2

Views: 2739

Answers (1)

dannymilsom
dannymilsom

Reputation: 2406

You will need to add some client side code (JavaScript) in addition to you server side code (Python).

A common approach is to use the jQuery ajax() method to send an ajax request to the server, handle this using your django application, send a response back to the client and then manipulate the DOM.

So your client side code needs to

  • send an XMLHttpRequest to the server (commonly using $.ajax())
  • modify the DOM if the request was successful (commonly inside the $.ajax() success callback function)
  • you might do this by iterating over the data in the JSON response to create the markup needed by the table row, and then replace the previous row with this new markup using JavaScript/jQuery (as shown here)

And your django application needs to

  • match the URL pattern inside a URL dispatcher
  • query your database inside the associated view
  • serialise the returned data into JSON (you can use the python JSON module)
  • return this JSON via a HttpResponse (this SO question talks about JSON and HttpResponses)

I also recommend you read this excellent answer about using django and ajax (including examples of the jQuery $.ajax() method).

It's also worth mentioning that you do not have to use jQuery for the ajax step - you can generate Ajax requests with pure JavaScript - however it is a popular approach and pretty user friendly.

Upvotes: 7

Related Questions