Invoking instance methods of Ajax XMLHttpRequest

function fetchJSONData(url, callback){
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.onprogress = function(event){
        console.log(event.loaded, event.total);
    };
    request.addEventListener('load', function(){
        if(request.status < 400){
            callback(request);
        }
    });
    request.send(null);
}

fetchJSONData('http://api.open-notify.org/astros.json', function(data){
    console.log(data.responseText);
});

I have a few queries:

1. What kind of event is passed to the function request.onprogress()?

2. Why am I unable to see request.onprogress() being called? Instead, there is a property with a value of null before it was initialized: Check screenshot in console

3. Is this event propagated to the function every time or only on event trigger? If it's upon event trigger, why can't I find

request.addEventListener('event', request.onprogress())
anywhere?

Answer №1

  1. When the XMLHttpRequest object's onprogress property is called, it means that the server has provided an update on the progress of the operation. This triggers the XHR's Progress event, where a specific function is set up to handle that event:

    function(event){
       console.log(event.loaded, event.total);
    } 
    
  2. The progress event is activated by updates from the server, and the timing of when this will occur is not precise. Generally, it happens approximately every 50 milliseconds for each byte transferred (as noted here: XmlHttpRequest onprogress interval).

  3. Each time the Progress event is triggered, the event is sent to your event handler. This enables you to access the values of event.loaded and event.total. With each invocation of the function, an updated event is passed along with fresh information.

In your code example, the progress event is not being connected using the DOM Event Model:

    request.addEventListener('event', functionToHandleEvent);

Instead, the progress event handling function is stored within the onprogress object property:

   request.onprogress = function(event){
      console.log(event.loaded, event.total);
   };

Although this approach registers your callback function, it relies on an older technique. The more standard (and modern) method would be as follows:

   request.addEventListener("progress", function(event){
        console.log(event.loaded, event.total);
   });

Answer №2

  1. What type of event is passed to the request.onprogress function?

As stated in the documentation, the event is passed an object with properties such as loaded and total.

  1. Why am I not seeing the invocation of request.onprogress?

The reason you are unable to see the invocation is because the remote endpoint () does not support CORS. Therefore, your AJAX request is not being sent. The progress event will only be triggered once the AJAX request is successfully made to report progress.

It's important to note that cross-domain AJAX calls are not allowed unless explicitly supported by the remote server.

3. Is this event passed to the function periodically or triggered by a specific event?

This event is triggered during the execution of the AJAX request.

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

Exploring the capabilities of JW Player 6 for seeking and pausing video

Is there a way to make JW Player 6 seek to a specific point and pause without pausing after each seek request, maintaining the ability to seek continuously during playback? The current solution provided pauses the player after every seek request, which is ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Unfortunately, I am currently unable to showcase the specifics of the items on my website

I am trying to create a functionality where clicking on a product enlarges the image and shows the details of the product as well. While I have successfully implemented the image enlargement, I am facing challenges in displaying the product details. Below ...

Leetcode Algorithm for Adding Two Numbers

Recently, I attempted the following leetCode Problem: However, I encountered an issue where one of my test cases failed and I'm unsure why. Here is the scenario: You are provided with two non-empty linked lists that represent two non-negative integ ...

Search for the location where the code is not functioning as intended

Take a look at this HTML code snippet: <input value="9961" name="c_id" id="c_id" type="hidden"> <input name="user_id" id="user_id" value="1" type="hidden"> <textarea id="comments" name="comments" style="width: 310px; resize: none; height: 7 ...

A guide to extracting the Jquery Version from the Chrome browser console while browsing webpages and transferring it to the Eclipse Java console using Selenium

Is there a way to retrieve the Jquery Version from Chrome browser console for webpages and transfer it to eclipse Java console using selenium? Try this command: $. ui. version https://i.sstatic.net/3bxA1.png ...

Refresh your inbox after sending a response by leveraging jQuery and AJAX requests

Let's talk about updating the messaging inbox after a user sends a reply, similar to Facebook's system. Here's how my messaging setup is structured: <div class="message_container"> <div class="message_inbox"> <di ...

concerns regarding the security of user availability names

When setting up a registration form, I included an ajax call to verify username availability. Although this functionality is helpful, I worry that it may make the system vulnerable to bots attempting to validate usernames. What measures can be taken to p ...

How can I obtain the model values for all cars in the primary object?

const vehicles={ vehicle1:{ brand:"Suzuki", model:565, price:1200 }, vehicle2:{ brand:"Hyundai", model:567, price:1300 }, vehicle3:{ brand:"Toyota", model ...

Customize your Bootstrap navbar dropdown to showcase menu items in a horizontal layout

I have been developing a new project that requires a navbar to be positioned at the center of the page, at the top. The current HTML code I am using is as follows... <div class="navbar navbar-inverse navbar-fixed-top center"> <div class="con ...

Using AngularJS to filter an array using the $filter function

Looking for a more elegant way to achieve the following task: myList.forEach(function(element){ if (!['state1', 'state2'].contains(element.state)){ myFilteredList.push(element) } }) I was thinking of using $filter('fi ...

Leveraging jquery $.ajax when handling window.onerror in Internet Explorer

Currently, I have a script that is functioning correctly on Firefox and Chrome, but I do not prioritize Safari compatibility. This script is designed to send an email whenever a JavaScript error occurs. However, I am facing an issue with Internet Explorer ...

What is the best way to extract user input from a bootstrap search bar and integrate it into an ajax request to fetch information?

I am currently utilizing HTML, Javascript, and bootstrap to develop a web application. However, I have encountered an obstacle. When using the code document.getElementById("input here"), it only returned an array of 0. My goal is to retrieve data from an A ...

Javascript: Accessing a shared variable within the class

Embarking on my JavaScript programming journey filled me with optimism, but today I encountered a challenge that has left me stumped. Within my tutorial project, there exists a class named Model which contains both private and public variables. Of particu ...

Issues with AngularJS Validation not functioning properly with File Inputs marked as 'Required'

I've been experimenting with this issue and haven't been able to solve it. While creating an Angular form, I found that validation works fine when the required attribute is used in a text field. However, when I tried adding a file input type with ...

Is it possible to refresh a div with just one click on an image?

I've tried searching, but I can't seem to find a clear explanation. Here's what I'm trying to achieve: I want to refresh specific divs on my webpage without having to reload the entire page. For example: <div id="topimage"> < ...

Manage SPA forms using Dataform Javascript - Safeguarding form information by avoiding inclusion in the URL

I have been using express, mongoose, and JavaScript to build a single page application. Everything seems to be working fine, except for one thing - I do not want the form data to show up in the URL when making a post request. I attempted to use a redirect, ...

CSS selector targeting the value inside a textbox

I am working in an environment that only supports CSS and Bootstrap 3.2, with no JavaScript functionality. My current task involves creating a list filtering solution using pure CSS selectors and HTML. Imagine I have 2 items within an HTML list element. T ...