Django, jQuery, XMLHttpResponse error
I am trying to learn basic ajax using Django. My simple project is an application that randomly selects Prize
from the available prizes in the database, reduces the number and returns prize.name
to the page.
I am using jQuery's $ .ajax method to pull this off. The only thing that works is the function error
defined in my $ .ajax call, but the error message says nothing but "error". I'm new to ajax, so I probably don't notice anything obvious. Here's the relevant code:
Model
class Prize(models.Model):
name = models.CharField(max_length=50)
quantity = models.IntegerField(default=0)
def __unicode__(self):
return self.name
bindings
urlpatterns = patterns('',
(r'^get_prize/$', 'app.views.get_prize' ),
)
View
def get_prize(request):
prizes = Prize.objects.filter(quantity__gt=0)
to_return = {}
if prizes:
rand = random.randrange(len(prizes))
prize = prizes[rand]
prize.quantity -= 1
prize.save()
to_return['prize'] = prize.name
data = simplejson.dumps(to_return)
return HttpResponse(data, mimetype='application/json')
else:
to_return['msg'] = "That all the prizes. No more."
data = simplejson.dumps(to_return)
return HttpResponse(data, mimetype='application/json')
Template
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User Conference Prize Randomizer</title>
<link rel="stylesheet" type="text/css" href="/static-media/style.css" />
<script type="text/javascript" src="/static-media/jquery-1.2.6.min.js"></script>
<script type="text/javascript">
var get_prize = function() {
var args = {
type: "GET",
url: "get_prize",
dataType: "json",
success: done,
error: function(response,error_string,e){
alert( "Error: " + response.responseText + " " + error_string );
for (i in e){
alert(i);
}
}
};
$.ajax(args);
};
var done = function(response) {
if(response) {
alert(response);
}
else {
alert("Something boo-booed");
}
};
$(document).ready(function() {
$("#start").click(get_prize);
});
</script>
</head >
<body>
<p><a href="" id='start'>Get Prize</a>, this link isn't working how I'd like.</p>
</body>
a source to share
This isn't entirely related to your question, but if you're trying to get a random object from the database, you can do this instead:
prize = Prize.objects.filter(quantity__gt=0).order_by('?')[:1]
if prize:
prize = prize[0]
# Using a slice prevents an exception if the query returns an empty queryset.
# If you're not a fan of LBYL, you could wrap the query in a try...except block instead:
try:
prize = Prize.objects.filter(quantity__gt=0).order_by('?')[0]
except IndexError:
# No more prizes pal...done, fini.
a source to share
This is not a direct answer to your question, but have you looked at the takonite jQuery plugin? This makes most AJAXy things trivial. Read more about the malup talonite page . While you're at it, check out its other great plugins .
a source to share