Loop through XMLHttpRequest requests

I have been attempting to send multiple server requests within a for loop. After coming across this particular question, I tried out the recommended solution. Unfortunately, it doesn't seem to be functioning as expected.

    for (var i = 1; i <= 10; i++)
    {
    (function(i) {
    if(<some conditions>)
    {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp[i]=new XMLHttpRequest();
      } else { // code for IE6, IE5
        xmlhttp[i]=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp[i].onreadystatechange=function() {
        if (xmlhttp[i].readyState==4 && xmlhttp[i].status==200) {
          document.getElementById("preselection").innerHTML=xmlhttp[i].responseText;
        }
      }
      xmlhttp[i].open("GET","getBuoys.php?q="+i,true);
      xmlhttp[i].send();
    }
})(i);
}

When I eliminate the for loop and swap all instances of xmlhttp[i] with just xmlhttp, the functionality works flawlessly for one element. However, I am encountering difficulties when attempting to send multiple requests. Any suggestions would be greatly appreciated. Thanks in advance.

Answer №1

Check out the code snippet provided below

// JavaScript
window.onload = function(){

    var fetchData = (function(){
        var xhr = [], index;
        for(index = 0; index < 3; index++){ //for loop
            (function(index){
                xhr[index] = new XMLHttpRequest();
                var url = "retrieve.php?info=" + index;
                xhr[index].open("GET", url, true);
                xhr[index].onreadystatechange = function(){
                    if (xhr[index].readyState === 4 && xhr[index].status === 200){
                        console.log('Data received from request ' + index + ' [ ' + xhr[index].responseText + ']'); 
                    }
                };
                xhr[index].send();
            })(index);
        }
    })();

};

// PHP [retrieve.php]
echo "Greetings Earthling -> " . $_GET["info"];

Output

Data received from request 0 [ Greetings Earthling -> 0]
Data received from request 1 [ Greetings Earthling -> 1]
Data received from request 2 [ Greetings Earthling -> 2] 

Answer №2

Initially, let's address the poor formatting. I kindly ask for improved readability in the future.

We can definitely tidy this up.

var XMLHttpRequest
  = XMLHttpRequest || require('xmlhttprequest').XMLHttpRequest;

// Initiates a request for 4 buoy page responses.
requestAllBuoys(4, function(requests) {

  console.log('Results received!');

  // Extract the responses, which are gathered in the order they were requested.
  responses = requests.map(function(request) {
    return request.responseText;
  });

  // It's up to you to decide how to handle the data on your page!
  updateDom(responses);

});

// Sends requests to all buoy URLs, invoking the specified callback once
// all requests have been completed with an array of XML requests.
function requestAllBuoys (n, cb) {

  var latch = makeLatch(n, cb);

  makeBuoyURLTo(n).map(function (url, i) {
    startXMLRequest('GET', url, latch.bind(undefined, i));
  });

}

// Generates a latch function, which will trigger the provided callback
// after being called n times.
function makeLatch (n, cb) {

  var remaining = n,
      results = [],
      countDown;

  countDown = function (i, result) {
    results[i] = result;
    if (--remaining == 0 && typeof cb == 'function') {
      cb(results);
    }
  }

  return countDown;

}

// Creates an array of buoy URLs from 1 to n.
function makeBuoyURLTo (n) {

  var i, buoyUrls = [];

  for (i = 1; i <= n; i++) {
    buoyUrls.push('getBuoys.php?q=' + i);
  }

  return buoyUrls;

}

// Builds and initiates an XML request, with the specified method and URL.
// The optional callback will be executed upon successful completion.
function startXMLRequest (method, url, cb) {

  var xmlRequest = createXMLRequest();

  xmlRequest.onreadystatechange = function () {
    if (isXMLFinished(xmlRequest)) {
      if (cb && typeof cb == 'function') {
        cb(xmlRequest, method, url);
      }
    }
  }

  xmlRequest.open(method, url, true);
  xmlRequest.send();

  return xmlRequest;

}

// Initiates an XML request using native HTML5 or MS ActiveX, depending on availability.
function createXMLRequest () {

  var xmlRequest;

  if (XMLHttpRequest) {
    xmlRequest = new XMLHttpRequest();
  } else {
    xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
  }

  return xmlRequest;

}

// Checks if the XML request has finished with a status of 200 (OK).
function isXMLFinished (xmlRequest) {
  return (xmlRequest.readyState == 4) && (xmlRequest.status == 200);
}

Although longer, this approach enhances clarity and the time invested in organizing it is time saved debugging.

It also provides access to the final results in a coherent array format. This is the main advantage.

It seems you have a solid grasp of the functionality, except for the DOM update (as it may just overwrite content rapidly).

Refer to this answer for assistance with handling asynchronous callbacks if needed. Maintain clean code for your own benefit.

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

List of duplicated BLE devices detected in network scanning

Greetings! I am currently working on an Ionic project named BLE Scanner. After facing some challenges, I finally managed to connect to the devices. Below is the code snippet that I discovered online: home.ts (please ignore the DetailPage) import { Compon ...

Creating a custom header in React for making AJAX requests

Need help setting header in Ajax Request using axios import React, { Component, PropTypes } from 'react' import { Link, browserHistory } from 'react-router' import { connect } from 'react-redux' import axios from 'axios& ...

What is the process for extracting the period value from SMA technical indicators within highcharts?

Can someone assist me in retrieving the period value from SMA indicator series by clicking on the series? series : [{ name: 'AAPL Stock Price', type : 'line', id: 'primary', ...

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Retrieving Data from Repeated Component in Angular 6

Need Help with Reading Values from Repeating Control in Angular 6 I am struggling to retrieve the value of a form field in the TS file. Can someone please assist me with this? This section contains repeating blocks where you can click "add" and it will g ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

The Bootstrap navigation bar drop-down feature is not displaying the menu

After skimming through various threads on stackoverflow regarding the dropdown box in the navigation bar, none of the solutions seem to address my issue. Utilizing bootstrap version 3, I've implemented the provided navbar example from the official si ...

The canvas will not show up, but it will magically appear on its own

Having trouble incorporating this script within a section or any other element? The script works perfectly on its own, but once loaded within a section, it fails to function properly. Below is the script in question; <!-- partial:index.partial.html --& ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Issue: [ng:areq] The parameter 'TasksCtrl' should be a function, but it is currently undefined

I seem to be encountering an error and I'm struggling to identify the cause. Is there something I overlooked? js var app = angular.module('Todolist', []); app.controller('TasksCtrl', [ '$scope', function($scope) { ...

Obtaining Public Data or Tags from Instagram with the Latest API: A Step-by-Step Guide

Is there a new way to access Instagram public profile data through the latest API update? After consulting Instagram's guidelines, I found the required steps: Start by creating an application with a specified site URL and redirect URL. Use oAuth to ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

Guide on inserting the elements <label>, <input>, and <span> into a <li> in a particular sequence

var btn = document.querySelector('.add'); var remove = document.querySelector('.draggable'); function dragStart(e) { this.style.opacity = '0.4'; dragSrcEl = this; ...

AJAX request triggers Internal Server Error 500

I encountered an "internal server error 500" while trying to access a certain action. When I inspect the element, it shows "Internal Server Error 500." The functionality works perfectly on my local environment, but when deployed on the client's serv ...

Having trouble with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

Implement a redux-form within a react-bootstrap modal

I am facing a challenge with incorporating a multipage 'redux-form' form into a react-bootstrap modal. My goal is to have the form displayed within the modal overlay when the modal is opened. How can this be achieved? The code below is producin ...

"Exploring the world of Ionic 2: uncovering its public variables

I'm facing an issue with Ionic 2, specifically with Angular. My concern revolves around a variable called "isConnected". I am unable to access it from an internal function within a function as it gives me an error saying "can't define property of ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...