I have a javascript variable called "counter", which I want to use to update a counter variable instantiated in models.py.
Here is a snapshot of models.py
class Player(BasePlayer):
#track the number of times the user has lost window focus
blur_quantity = models.IntegerField(initial=0)
Here is an example of pages.html
{% block content %}
<button name="blur_button" value=counter onclick="Warn()" class="btn btn-primary btn-large">Blur Button</button>
{% endblock %}
{% block scripts %}
<script>
var counter = 0;
// Tracks window blurs
$( document ).ready(function() {
function onchange (evt) {
counter++;
console.log(counter);
}
window.onblur = onchange;
});
function Warn() {
alert(counter);
}
</script>
{% endblock %}
Now, whenever the user clicks the button, the value of "counter" should be stored somewhere. How do I update the value of blur_quantity in models.py (e.g. my Django database) to reflect the value attached to the blur_button?
JavaScript:
var counter = 0;
$( document ).ready(function() {
function onchange (evt) {
counter++;
$.ajax({
url: '/update_counter/',
data: {'counter': counter},
type: 'POST'
}).done(function(response){
console.log(response);
});
}
window.onblur = onchange;
});
views.py:
from django.http import HttpResponse
from models import Player
def update_counter(request):
if request.method == 'POST':
player = Player.objects.get()
player.blur_quantity = request.POST['counter']
player.save()
message = 'update successful'
return HttpResponse(message)
urls.py:
from django.conf.urls import url
from views import update_counter
urlpatterns = [
url(r'^update_counter/', update_counter)
]
Basically, the ajax in call in the JavaScript sends counter to the server via a POST request. urls.py routes the request to your update_counter method, which updates the database with the value of counter. Finally, the update_counter method returns a response, which is handled by the done function in the JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With