5👍
✅
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.
1👍
Inside the onChange
method, you can send a POST
request to one of your server’s endpoint, and let the server updates the database from there. Then the server shall respond back as a response to that POST
request with the most updated value of blur_quantity
, and use this value as your new counter
.
Source:stackexchange.com