Currently, I'm in the process of developing a basic "rock paper scissors" game with CSS animations incorporated. The majority of the functionality is managed via JavaScript, as my primary focus right now is learning JS.
The user versus computer match also takes place within the JavaScript. Once the match concludes, the experience points earned by the user are stored in a new variable.
My current task involves transmitting this data (earned exp) to the views so that it can be saved back into a database field (users.exp).
I believe utilizing jQuery ajax or fetch API should facilitate this, but despite several hours of attempts, I seem to be struggling with understanding it completely.
Can anyone provide me with some tips or an explanation? I'm more interested in understanding the solution rather than just getting one handed to me.
Views:
@login_required
def profile(request):
if request.user.is_authenticated:
user = request.user
userObj = Profile.objects.filter(user=user)
usersLevel = userObj[0].level
usersPoints = userObj[0].points
context = {
'usersLevel': usersLevel,
'usersPoints': usersPoints,
}
return render(request, 'rps_app/game.html', context)
else:
print('No user logged in!')
return render(request, 'rps_app/game.html')
This snippet represents my template where I load the users' data:
<script type="text/javascript">
var usersLevel = '{{usersLevel|safe}}';
var usersPoints = '{{usersPoints|safe}}';
</script>
JavaScript Code:
let users_level = Number(usersLevel);
let users_points = Number(usersPoints);
progressbar.style.width = `${users_points}%`;
...
More JavaScript:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/game',
csrfmiddlewaretoken: "{{ csrf_token }}",
type: 'get',
success: function(data) {
console.log(data);
alert(data);
},
failure: function(data) {
alert('Your code is crap mate');
}
});
});
})
************ . E D I T E D . ***********
Here's my latest attempt:
JavaScript:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/test/earned_exp=100/',
csrfmiddlewaretoken: "{{ csrf_token }}",
success: function(data) {
alert('success');
},
failure: function(data) {
alert('Your code is crap mate');
}}); });})
Views:
def pass_variable(request, earned_exp=None):
some_variable = request.GET.get('earned_exp')
console.log(some_variable)
return HttpResponse('<h1>ok.{}</h1>'.format(earned_exp))
URL:
path('test/<earned_exp>/', user_views.pass_variable, name='pass_variable'),