JavaScript: XHR struggles with managing multiple asynchronous requests

Hey there, I'm currently attempting to access a single resource multiple times with various parameters. Here's what I have so far:

Essentially, I am making requests for the following domains:


var domains = [
'host1',
'host2'
];

var requests = new Array();

for ( i in domains )
{
    requests[i]=new request(domains[i]);
}

function request(site)
{
    var url = 'get_remote_status.php?host='+site;
    var queues = {};
    http_request = new XMLHttpRequest();
    http_request.open("GET", url, true, 'username', 'password');
    http_request.onreadystatechange = function () {
        var done = 4, ok = 200;
        if (http_request.readyState == done && http_request.status == ok) {
            queues = JSON.parse(http_request.responseText);
            var queuesDiv = document.getElementById('queues');
            print_queues(queues, queuesDiv, site);              
        }
    };
    http_request.send(null);
}

However, it seems that only one of these requests is being processed by the code lambda. While Chromium indicates that both requests have been received and are visible in the resources pane.

If I switch the request to synchronous, it works fine. But this approach is not suitable for the release code as a request may time out.

Thank you for your help.

Answer №1

Describe the creation of http_request using the keyword var. Currently, the XHR object is being assigned to a global variable which limits your script to handling only one XHR at a time.

Here is the relevant code:

function request(site)
{
    var url = 'get_remote_status.php?host='+site;
    var queues = {};
    http_request = new XMLHttpRequest();

Suggested revision:

function request(site)
{
    var url = 'get_remote_status.php?host='+site;
    var queues = {};
    var http_request = new XMLHttpRequest(); //VAR VAR VAR !!!

By not including var before a variable, it will be defined globally (window). Using var ensures that the variable is defined locally (in function request, in this case).

Answer №2

Running multiple asynchronous XHR calls is indeed possible, but it requires assigning a unique identifier to each call in order to store and retrieve them locally within your DOM.

For instance, if you need to iterate over an array and make an Ajax call for each object, the following code may be useful:

var xhrCollection = {};
for (var k=0; k<dataValues.length; k++){
    var dataValue = dataValues[k];
    
    // Check for Ajax link availability
    if(typeof dataValue.ajaxLink != 'undefined'){
        var elementHtml = '<div id="' + dataValue.id + '_' + itemKey + '" class="item col-xs-12 ' + dataValue.classes + '"><div class="label">' + dataValue.label + ' :</div><div id="'+ k +'_link_'+ dataValue.id +'" class="value">'+dataValue.value+'</div></div>';
        
        mainWrapper.find('#' + itemKey + ' .body').append(elementHtml);

        xhrCollection['xhr_'+itemKey] = new XMLHttpRequest();
        xhrCollection['xhr_'+itemKey].uniqueId=''+ k +'_link_'+ dataValue.id +'';
        
        console.log(xhrCollection['xhr_'+itemKey].uniqueId);
        
        xhrCollection['xhr_'+itemKey].open('POST', dataValue.ajaxLink);
        xhrCollection['xhr_'+itemKey].send();
        
        console.log('Data sent');
        
        xhrCollection['xhr_'+itemKey].onreadystatechange=function() {
            if (this.readyState == 4) {
                console.log(''+this.uniqueId);
                document.getElementById(''+this.uniqueId).innerHTML = this.responseText;
            }
        };
    }
}

Remember to store each XHR object in a global variable object and define a value

xhrCollection['xhr_'+itemKey].uniqueId
to access its unique identifier and display its result appropriately.

I trust this information will prove beneficial to you in your endeavors.

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

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

The cookie being sent from the backend API (implemented in nodeJS using express) to the frontend (developed with NextJS) is not successfully setting in the

I'm currently working on a NextJS app running on localhost:3000 and a node express API running on localhost:3030. I have encountered an issue where, after sending a request from the frontend to the backend login route, I am trying to set a cookie call ...

A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 differ ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

I am consistently running into an Uncaught Syntax error within my Express server.js while using Angular 1.5.6

I've been struggling for hours to integrate Angular with routes that I've created. Eventually, I decided to give Express a try and set up a basic server.js file to run as a standalone server. However, nothing seems to be working and I keep encou ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

Breaking or wrapping lines in Visual Studio Code

While working in Visual Studio Code, I often encounter the issue of long lines extending beyond the screen edge instead of breaking and wrapping to the next line. This lack of text wrapping can be quite bothersome. I utilize a split-screen setup on my co ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

What is the best way to adjust the value of largePageDataBytes in Next.js?

I am looking to modify the largePageDataBytes setting, despite knowing it may impact performance. I made an attempt in next.config.js with the following code: /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options h ...

In an HTML template, what is the significance of the $ symbol?

Currently, I am exploring the web.py framework with the help of a tutorial that I found online. This tutorial focuses on Python and AJAX functionalities. One thing that is confusing me in the tutorial is the use of variables with a $ sign in the tutorial ...

The disabled functionality of AddCircleIcon in Material UI seems to be malfunctioning

The AddCircleIcon button's disabled functionality is not working, even though the onClick function is functioning properly. Even when directly passing true to the disabled property, it still doesn't work. I am in need of assistance to resolve thi ...

Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript. Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate ...

I'm having trouble receiving a response after uploading an image on Cloudinary using React js

Once the image is uploaded using the API, it should return a response. However, I am not receiving any response through the API even after uploading the image. if (pic.type === "image/jpeg" || pic.type === "image/png") { const da ...

Connect data from an HTML table depending on the chosen option in a dropdown menu using AngularJS, JQuery, JSON, and

Could you please correct my errors? It's not working as I have made some mistakes. I need an HTML table based on the selection. I have tried but cannot find a solution. I created a dropdown, and if I select any value from the dropdown and click a butt ...

What is the simplest method for comparing transaction amounts?

I'm in the process of integrating PayPal into my website using their REST API. My goal is to allow users to input the amount they want to deposit. While I can obtain the total during payment creation, I'm unsure how to smoothly pass it to the exe ...

Locating the top 3 largest values in an HTML data table and highlighting them in red

Issue Description: I am working with data that displays the electricity consumption of different buildings in HTML tables. There is a possibility that these tables may contain duplicate values. With the use of jQuery, I am seeking a method to identify an ...

What is the best way to retrieve duplicate input values using JavaScript?

Hey there! I have created a button that, when clicked, will add two input fields one after the other. I achieved this using the clone() function. However, my issue arises when I input values into each field and then click the submit button, as I only recei ...