In order not to refresh the page, yes, you will need AJAX. I usually do not like to offer libraries too many answers, however, in the interest of ensuring compatibility with several browsers, I would suggest using jQuery .
With jQuery, it will be as easy as
Inside your django template
<html> ... <head> <script> var URL = "{% url 'my_view_that_updates_pieFact' %}"; </script> </head> ...
Later...
You will need either POST or GET data to the server through AJAX. To be more RESTful, whenever I need to send data to the server, I use POST. jQuery provides the convenience function $. post () for AJAX data to a URL via POST. Three parameters are the URL, the data to send (as a JavaScript object, read python dictionaries if you are not too familiar with JavaScript), and the callback function when the server sends a response.
<script> function updatePieFact(){ var data = {'pieFact': pieFact}; $.post(URL, data, function(response){ if(response === 'success'){ alert('Yay!'); } else{ alert('Error! :('); } }); }
The .click() functions basically match the onlick directions in the html attribute. Both click events update pieFact , as you would expect, and then call updatePieFact() to send the pieFact value to the server.
$(document).ready(function(){ $('#bttnMinus').click(function(){ pieFact *= 0.9; updatePieFact(); }); $('#bttnPlus').click(function(){ pieFact *= 1.1; updatePieFact(); }); }); </script>
In views.py
Since I used the $.post() function in JavaScript, the request that Django is about to receive will have a "POST" method, so I check if the method is really POST (this means that if someone visits the URL of this view with something like a GET request, they wonβt update anything). As soon as I see that the request is essentially POST , I check if the key 'pieFact' in the dict request.POST .
Remember when I set the data variable in javascript to {'pieFact': pieFact} ? This javascript just becomes a python request.POST dictionary. So, if in javascript I used var data = {'hello': pieFact}; then I would check if 'hello' in request.POST . Once I see that pieFact is in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponse with the string 'success' . This correlates with validation in javascript: if(response === 'success') .
def my_view_that_updates_pieFact(request): if request.method == 'POST': if 'pieFact' in request.POST: pieFact = request.POST['pieFact']
Hope this makes you point in the right direction.