user9549517
user9549517

Reputation:

Passing variable from javascript to django views

I am creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what I am focusing on mostly at the moment.

User vs computer match also happens in javascript. When match is finished I am assigning users earned exp(points) to new variable.

What I am trying to do now is sending that data (earned exp) to the views, so I can save it back in a database (users.exp).

I think jQuery ajax or fetch api should do that if I am right but after hours of trying I probably just don't get it.

Any1 can give me some tips, explanation? Not just solution please.

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 is my template where Iam loading users data:

<script type="text/javascript"> 
        var usersLevel = '{{usersLevel|safe}}';
        var usersPoints = '{{usersPoints|safe}}';
</script>

js:

let users_level = Number(usersLevel);
let users_points = Number(usersPoints);
progressbar.style.width = `${users_points}%`;
...

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 . ***********

Thats what I got now:

js:

$(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('succes');
            },
            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'),

Upvotes: 1

Views: 739

Answers (1)

Sahil
Sahil

Reputation: 1413

You can pass variables as URL parameters and get them through the request object.

$.ajax({
    url: 'mycoolwebsite.com/path/?earned_xp=100'
    success: function(e){
       alert("success");          
    },  
    error: function(e){
       alert("error")
    }   
});


class MyView(View):
    def get(self, request):
       xp = request.GET.get("earned_xp")
       # do whatever you want with the XP now.

In case you want to send multiple URL parameters, you can seperate them by & here's an example url

https://example.com/?hello=world&goodbye=coding

Upvotes: 0

Related Questions