Transferring data from JavaScript to Django views

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'),

Answer №1

If you need to pass variables as URL parameters and access them using the request object, it's possible.

$.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")
       # You can now manipulate the XP data however you like.

To include multiple URL parameters, separate them with &. Here's an example URL:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing a single JavaScript array in separate arrays depending on a specific condition

I have a JavaScript array variable where each element is an object with values like: {"ID":10075,"SPECIALIZATIONID":"17","PRESPCIALIZATIONID":11,"GROUPID":1} The entire JSON.stringify value looks like this: "[{"ID":10075,"SPECIALIZATIONID":"17","PRESP ...

ajax form submission does not yield any results

Trying to troubleshoot an issue in my code - it functions properly when submitted without ajax. When submitting my form with empty fields, the controller should return errors but is returning nothing. Here is my JavaScript: $.ajaxSetup({ headers: { ...

How can we apply position: fixed in print media queries using CSS?

In order to display a footer on every printed page, we have implemented the use of position: fixed. However, one issue that has arisen is that content ends up flowing underneath the footer. Is there a solution to prevent this from happening while still k ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Unable to change the name of the file using ngx-awesome-uploader

Currently, I am utilizing https://www.npmjs.com/package/@sleiss/ngx-awesome-uploader and facing an issue regarding renaming files before uploading them. Upon reviewing the available methods, it appears that there is no option for file renaming. While I c ...

Utilize ajax to access the AWS Support Service

I am attempting to utilize the "create case" option in AWS support service to generate a case. My goal is to create AWS support tickets from a web application, but I am encountering CORS as the main obstacle (not surprising :p). Is it possible to create AW ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

One effective method for populating my form following the retrieval of JSON data

Currently, I am working on a VueJs project where I am fetching data from a Mysql database using Axios. My next step is to implement an edit option for user profiles. I am wondering what the most efficient method is for populating the form with the fetche ...

Manage the Cancel button functionality in Safari/Chrome when dealing with the Open in App Store pop up

Is there a way to manage the Cancel button on the Open in App prompt when redirected from Safari/Chrome to the AppStore? The situation is as follows: A user is prompted to download the app via a browser link. Upon clicking the link, it determines whether ...

How to fetch a pre-existing file with CodeIgniter

Currently, I am in the process of creating a website that allows users to download jpg, png, pdf, and docx files uploaded by an administrator. The file uploading functionality is working smoothly without any issues. Upon uploading a file, its name is stor ...

Tips for saving IP addresses in the database with Django admin

Is it possible to store the IP address of every visitor to a website? What would be the most effective method to achieve this? Say, for example, we have a model: class IPAddress(models.Model): pub_date = models.DateTimeField('date published' ...

Showing a DataTable row within a pop-up modal

I'm facing an issue with rendering datatable content inside a modal after setting up the datatable and modal for row click functionality. I need each column of the row to display information under a unique span class. Below is my HTML structure. The ...

Steps for making a CSS animation that horizontally moves an element

I've been working on a React project that features a horizontally scrolling banner. The animation for the automatic scroll is set up like this: "@keyframes marquee": { "0%": { transform: "translateX(0);" }, &quo ...

I'm looking for an algorithm in PHP5 that can effectively synchronize data between local and online databases. Are there

Looking for a way to synchronize data between two databases, one online and the other local. Does anyone know of an algorithm using PHP5 that can accomplish this task? ...

Is there a way to retrieve the ID by using the autocomplete feature to search for a user's first name and last name in PHP

Check out this code from index.php (all credit to the original owner): <HTML> <HEAD> <TITLE> Ajax php Auto Suggest </TITLE> <link href="css/style.css" rel="stylesheet" type="text/css"> <SCRIPT LANGUAGE="JavaScript ...

Retrieve the obscured product identification number from the database for use in the jQuery autocomplete plugin roster

Currently, I am using a jQuery autocomplete plugin in my project to select data from a database using PHP, MySQL, and Ajax. While the plugin is working well overall, I am facing an issue when it comes to fetching the product_id along with the product_name. ...

Comparing Ajax HTML with XML/JSON responses: which is better for speed or other considerations

I have a website that heavily relies on ajax, and I insert around 3k html formatted pages into the DOM through ajax requests. My current approach involves inserting the entire html responses using jQuery. However, another option is to output in xml or jso ...

Issue encountered while attempting to parse JSON data

I've been dealing with JSON data in Django view and parsing it in JavaScript to extract the necessary information. This is a snippet from my view.py file (Django) ibms = [] for i in range(2, 5): ibm = Mapa(i, wsMapa) ibms.append(ibm.__dict__) ...

Incorporate AngularJS {{expression}} into ng-repeat by utilizing a separate array

After completely rebuilding my website (which was originally hacked together with Wordpress), I decided to utilize Laravel and AngularJS. The transition has been quite challenging, but I'm almost there, except for one issue. On my website, I have &ap ...

Using Django to show NullBooleanField as a Radio button with a default value of None

I have been able to implement NullBooleanField as radio buttons in multiple ways, but I am encountering an issue with setting the default value to None. Here is my code snippet: models.py: class ClinicalData(models.Model): approved = mode ...