I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with \"+\" and \"-\" buttons, which should increment a variable c
In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of jQuery.
<html>
...
<head>
<script>
var URL = "{% url 'my_view_that_updates_pieFact' %}";
</script>
</head>
...
You'll need to either POST or GET the data to the server via AJAX. To be more RESTful, whenever I need to send data to the server I use POST. jQuery provides the $.post() convenience function to AJAX data to a url via POST. The three parameters are the URL, the data to send (as a JavaScript object; think python dictionaries if you're not too familiar with JavaScript), and a callback function once the server sends back 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 are basically the same thing as specifying onlick
in the html attribute. Both click events update pieFact
as you would expect and then call updatePieFact()
to send the value of pieFact
to the server.
$(document).ready(function(){
$('#bttnMinus').click(function(){
pieFact *= 0.9;
updatePieFact();
});
$('#bttnPlus').click(function(){
pieFact *= 1.1;
updatePieFact();
});
});
</script>
Since I've used the $.post()
function in the JavaScript, the request that Django is going to receive is going to have a method of "POST"
, so I check to make sure that the method is indeed POST
(this means that if someone visits the URL for this view with something like a GET request, they won't update anything). Once I see that the request is, in fact, a POST
, I check to see if the key 'pieFact'
is in the dict request.POST
.
Remember when I set the variable data
in the javascript to {'pieFact': pieFact}
? That javascript just becomes the request.POST python dictionary. So, if in the javascript I had instead used var data = {'hello': pieFact};
, then I would be checking if 'hello' in request.POST
instead. 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 the check 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']
# doSomething with pieFact here...
return HttpResponse('success') # if everything is OK
# nothing went well
return HttpRepsonse('FAIL!!!!!')
Hopefully that will get you pointed in the right direction.