"Run JavaScript code within the boundaries of the start and end of XMLHttpRequest

Currently, I am using XMLHttpRequest to execute an AJAX request without the use of jQuery, relying solely on plain old Javascript. This particular AJAX request may take some time as it calls an endpoint responsible for processing transactions.

In order to keep track of the transaction status in real-time, I intend to refresh this information on the screen while the asynchronous AJAX request is ongoing. To achieve this, I plan to make a 'progress' transaction through another GET AJAX request.

My exploration of the XmlHttpRequest object led me to experiment with the onprogress attribute. However, I discovered that it does not provide the functionality I envision, which resembles a while loop.

In pseudo code, my approach would look something like this:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'process/', true);
    xhr.send();

    // Create a loop to call another process repeatedly while the request is pending

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log("Request Successful");
            } else {
                console.log("Request Failed");
            }
        } else {
            console.log("Request State changed but not complete");
        }
    }

Despite several attempts, I have been unable to solve this issue. My initial idea was to implement a while loop based on a scoped value, assuming the asynchronous nature of the request would update this value to break the loop. However, this solution did not yield the expected results.

I believed this scenario might be quite common, especially for progress bars, yet I failed to find a suitable solution. Is there a fundamental aspect I am overlooking?

Answer №1

In my usual manner, I managed to solve this shortly after posting.

I configured the function to be called every second, then eliminated the interval once the request was finished:

    let timerId;
    xhr.onloadstart = function (e) {
        timerId = setInterval(function () {
            myProgressFunction();
        }, 1000)
    };
    xhr.open('GET', '/process', true);
    xhr.send();
    xhr.onloadend = function (e) {
        clearInterval(timerId);
    };

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

Which data structure is suitable for storing a JSON object?

Currently, I have a form set up in the following way: using (Ajax.BeginRouteForm( ... new AjaxOptions { HttpMethod = "POST", OnFailure = "OnFailure", OnSuccess ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

Leveraging the power of Javascript/jQuery to manipulate form

On my website, I have implemented a form that requires a customized response for certain zip codes. To achieve this, I am developing a code that validates the first 3 digits of the entered zip code against a predefined array in my system. Although the code ...

Passing array map data to another screen in React Native

Greetings! I successfully created an array map to showcase specific data from my API. Now, I am faced with the challenge of TRANSFERRING THIS DATA TO ANOTHER SCREEN. My current dilemma lies in the fact that the displayed data is generated using ARRAY MAP, ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

Tips for ensuring jwt token is not lost when refreshing a page in an angularjs app

My project involves authorizing users using jwt tokens, but I am facing an issue where the token is lost upon page refresh and subsequent requests to the server do not include the token. The setup includes storing the token in local storage and utilizing ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Utilizing jQuery's AJAX POST method to send a POST request within the Phoenix Framework

Our goal is to utilize the content editable feature, leveraging the routes generated in router.ex: pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :put_secure_browser_headers end pipeline :api ...

Incorporating EJS Template Body Parameters into AWS Lambda's Handler.js Using Serverless.yml

I have a scenario where I am trying to embed an EJS template named 'ui.ejs' into my handler.js file. The goal is to extract URL query parameters, then pass them to a function called 'ui.js' to retrieve data, which will then be displayed ...

To add additional nested data to a JSON object in JavaScript, you can use the push method or update

Looking to enhance the nested object data within my existing object The current structure of the JSON object array resembles this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ ...

Tips on Avoiding Connection Timeouts in jQuery AJAX

Currently, I am encountering an issue with a connection time out during a jQuery ajax operation. The situation is that when I send an ajax request, it takes too long to be processed by the server (about 5 minutes). To address this delay, I have implemented ...

No overload error encountered with TypeScript function call

I am working on an async function that communicates with the backend and I need it to handle axios error messages. My goal is to display these messages in a form. export async function register( prevState: string | undefined, formData: FormData ) { t ...

Perform an Ajax POST request to a specific URL and then automatically redirect to that same

I am currently in the process of developing a web application that allows users to create markers on a Leaflet map. The marker details are then saved in a Django backend system. My objective is to direct the user to a detailed page where they can input mar ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Is it possible to alter the value and label of an HTML button in a permanent manner?

I am developing a personalized management system that records your activities from the previous day based on the buttons you clicked. I have successfully implemented the ability to edit these activity buttons using jQuery, but I would like these changes to ...

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...