Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Dynamic Javascript Variable to Django/Python

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 called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time the value is changed. This will be used to update the size of pie charts in a web map. I have the following:

<button type="button" id=bttnMinus onclick="pieFact=pieFact*0.9">-</button>
<button type="button" id=bttnPlus onclick="pieFact=pieFact*1.1">+</button></td> 
<script type="text.javascript">
    var pieFact=0;
</script>

How can I pass the value of "pieFact" to Django? Based on my limited knowledge, I think I may have to use AJAX post/get.

like image 769
Jason Hawkins Avatar asked Jun 10 '14 23:06

Jason Hawkins


1 Answers

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.

With jQuery it would be as simple as

Inside of your django template

<html>
    ...
    <head>
        <script>
            var URL = "{% url 'my_view_that_updates_pieFact' %}";
        </script>
    </head>
...

Later on...

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>

In views.py

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.

like image 156
OozeMeister Avatar answered Oct 03 '22 00:10

OozeMeister