Josh Josh - 4 months ago 14x
Javascript Question

Refresh a div in Django using JQuery and AJAX

I am trying to refresh a certain part of my page with AJAX and JQuery (in Django). How can I get it to redisplay only the div, rather than the whole page.

// In my template
var tag_cloud_floor = function(floor) {
$.ajax({ url: "/{{ user }}/{{ tag }}/",
data: {tag_cloud_floor: floor},
type: 'POST',
success: function(data) {


Here is my view.

def tag_page(request, username, tag):
if username == request.user.username:
tags = request.user.userprofile.tag_set.all()

if request.is_ajax() and request.POST:
floored_tags = []
for t in tags:
if t.item_set.all().count() >= int(request.POST['tag_cloud_floor']):
tags = floored_tags

tag = Tag.objects.get(title=tag)
items = tag.item_set.all()
return render_to_response("tag_page.html", { 'user': request.user ,
'tag': tag,
'tags': tags,
'items': items })
return HttpResponseRedirect('/' + request.user.username + '/')

Currently, it places the entire html page into the #tag_page div. I want it to replace the old #tag_page div with the new #tag_page div. If I replace
it refreshes the whole page to how it should be, but I figure refreshing the whole page is a waste.

If there is a better way to do this, let me know.


First, it looks like your code is broken - this is not a valid Javascript/jQuery instruction:


You need to add the missing quote:


As for refreshing only a single div, I would extract contents of that div to a separate template my_div.html, include it in the main page template using {% include "my_div.html" %}. Then, in my AJAX view, I would render and return only that rendered my_div.html.