Unusual behavior: Django app not triggering Ajax XHR onload function

I'm currently working on a Django app that features user posts, and I'm in the process of implementing a 'like' / voting system. Initially, I set up this functionality using complete page refreshes combined with a redirect after the vote was made to update the like count. However, I recently learned about ajax and how it enables partial page updates without the need for a full reload.

let up_vote = document.getElementById("up-vote").addEventListener('click', () => {
    console.log("clicked");
    let xhr = new XMLHttpRequest();
    xhr.open('GET', "{% url 'up-vote' %}", true);
    console.log(xhr);
    xhr.onload = () => {
        console.log("inside");

    };
    console.log("outside");
});

My current javascript code functions as described above. When clicking "up-vote," the console logs "clicked" along with the xhr object. However, the onload event seems to be skipping as "inside" is never printed, instead jumping straight to "outside."

I suspect that the problem lies with the URL path, but I'm unsure how to rectify it. The file structure of my app is organized as follows:

app
|-static/app  
    |-scripts/*this js file*/  
    |-images  
    |-styles  
|-templates/app  
    |-html files
|-views.py *which handles the request*
|-urls.py

Within urls.py,

urlpatterns = [
    ...
    path('post/<int:pk>/up/', up_vote, name='up-vote'),
    ...
]

and views.py contains the following:

@login_required()
def up_vote(request, pk):
    print("HI")
    obj = get_object_or_404(Post, pk=pk)
    uid = request.user.id
    if not obj.votes.exists(uid):
        obj.votes.up(uid)
    data = {
        'votes': obj.votes.count()
    }
    return JsonResponse(data)

Any assistance or guidance would be greatly appreciated :)

p.s. I also attempted using xhr.onreadystate, which led me to believe there might be an issue with the URL path.

Answer №1

When making an AJAX request (as the name suggests), it operates asynchronously, allowing it to pass through directly to the 'outside'.

Furthermore, remember to execute xhr.send()

let up_vote = document.getElementById("up-vote").addEventListener('click', () => {
    console.log("clicked");
    let xhr = new XMLHttpRequest();
    xhr.open('GET', "{% url 'up-vote' %}", true);
    console.log(xhr);
    xhr.onload = () => {
        console.log("inside");
    };
    xhr.send()
    console.log("outside");
});

Note: It appears that there may be issues with your URL/views configuration. Your view and routes seem to require a pk, yet your {% url 'up-vote' %} is not passing a pk parameter to it.

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

Error: Unable to iterate through the {(intermediate value)}. It's not a function

Snippet of the original code: const genreOptions = [{{ genreOptions | json_encode | raw }}].map((type , label) => ({value: type, label: label})); Piece of debugging code: const genreOptions = { "Horror": "Kork ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Guide to retrieving IDs of images on a canvas during drag and drop functionality

I've developed a finite state machine drawing tool that includes drag-and-drop functionality for different images, such as states and arrows. Each arrow creates a div tag for the transition, with unique ids assigned to every state, arrow, and transiti ...

The Django application is failing to interact with the AJAX autocomplete functionality

After typing the term "bi" into the search bar, I expected to see a username starting with those initials displayed in a dropdown list. However, nothing is showing up. Here are the codes I have used: search.html <html> <div class="ui-widget"> ...

Managing ajax requests, failing to retrieve information

I am struggling to configure my client-side ajax calls to send data to a node express server. I want the ajax request to be triggered "onclick" of an href link. My goal is to pass the ID of the link as a variable to the server, but unfortunately, the serv ...

I'm puzzled as to why my JavaScript code only functions correctly when I place it after the HTML, despite having a window.onload event handler in place

Just beginning my journey in a CS class and seeking guidance for my lack of basic knowledge. I've noticed that this JS code only works if placed after the HTML, not within the head tag. Shouldn't window.onload handle that? Can someone clarify wha ...

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

What is the best method for determining the cookie expiration time in AngularJS 1.3?

Currently in my application, I am utilizing AngularJS 1.3. I encountered a challenge while using $cookies to store data where I needed to implement a 1-minute expiration time for the cookie. However, the $cookies service in AngularJS 1.3 does not provide ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...

What is preventing window.scrollTo() from being executed?

I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is togg ...

Error encountered with react-query and UseQueryResult due to incorrect data type

I'm currently implementing react-query in my TypeScript project: useOrderItemsForCardsInList.ts: import { getToken } from '../../tokens/getToken'; import { basePath } from '../../config/basePath'; import { getTokenAuthHeaders } fr ...

Identifying page elements in Protractor when they lack obvious identifiable properties

Scenario Here is the HTML code snippet using an Angular JS template: <div class="data-handler-container"> <div class="row"> <div class="data-handler" ng-if="dataController.showDistance()"> <p>{{ 'Item ...

Show a toast message and reset the form upon submission

Here I have created a contact form using HTML, CSS, and JavaScript. However, I'm facing an issue where the form redirects me to a page displaying the submitted details after clicking the submit button. I want to display a toast message instead and res ...

Verify user identity before sending directory in Express

I'm encountering an issue with authenticating users before they access an express directory file tree. While I can successfully authenticate users on all other pages, I'm facing difficulties with authentication on "/dat/:file(*)" even though I ha ...