Ajax update using Django and Prototype
This tutorial will show how to update a list of objects using Ajax and jQuery.
Suppose to have a page that shows all snippets for a given language (for example python).
Then we want to be able to load all ruby snippets without refreshing the page.
Let’s see the html for the “list” page:
{% for snippet in snippet_list %}
<div id="snippet-detail-{{snippet.id}}">
<!-- snippet content here -->
</div>
{% endfor %}
</div>
Suppose to have a button for the python language and an other for the ruby language.
We want to load all sippets for the currently selected languages: we only need to associate following javascript function on “onclick” event of the button:
<input type="button" id="rb-input" onclick="loadSnippets('rb');"></input>
<script>
function loadSnippets(language)
{
new Ajax.Updater('snippetListContainer', '/snippets/update_index/'+language, {asynchronous:true});
}
</script>
This javascript function calls asynchronously the server; then it will updates the “snippetListContainer” with the call’s response.
Now let’s see the code for the view:
"""
Renders the list of snippets basing on selected button.
This method is called by an Ajax request that starts every time a user clicks on a lanuage language button
Context::
snippet_list
the list of snippets to display in the page
Template::
myapp/snippets/index_included.html
"""
snippet_list = db.GqlQuery("SELECT * FROM Snippet WHERE language_code = :1 ORDER BY pub_date DESC", language)
return render_to_response('myapp/snippets/index_included.html',
{'snippet_list' : snippet_list},
context_instance=RequestContext(request))
And finally this is the code to place in the “url.py” file:
urlpatterns += patterns('',
(r'^snippets/update_index/(?P<language>[\w-]+)$', snippets.update_index),
)