Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) {
    using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() {
       if (x.state == 4 && x.responseCode == 200) notifyUser(i);
    }
}

My goal now is to ensure that every time the state reaches 4, the correct value of i is alerted based on the URL requested. Currently, it only alerts once with a value of 5.

Answer №1

If you're looking to utilize the with statement to keep track of i, there are a couple of ways to achieve this. One option is to include i within an object that also contains a reference to the xhr object:

for (var i = 0; i < 5; i++) {
    with ({i: i, xhr: new XMLHttpRequest()}) {
        xhr.open("GET", "d.php?id=" + i);
        xhr.send(null);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200)
                alert(i);
        }
    }
} 

Alternatively, you can create the xhr object outside of the with statement and attach i to it like so:

var xhr;
for(var i=0; i<5; i++){ 
    (xhr = new XMLHttpRequest()).i = i;
    with(xhr) {
        open("GET","d.php?id=" + i);
        send(null);
        onreadystatechange=function(){
            if (readyState == 4 && status == 200)
                alert(i);
        }
    }
} 

For a more robust solution that is future-proof, consider defining the handler within a variable scope that provides access to the necessary variables:

function doRequest(i, xhr) {
    xhr.open("GET","d.php?id=" + i);
    xhr.send(null);
    xhr.onreadystatechange=function(){
        if (xhr.readyState == 4 && xhr.status == 200)
            alert(i);
    }
}

Then, invoke the function as follows:

for(var i=0; i<5; i++){
    doRequest(i, new XMLHttpRequest());
} 

Alternatively, if you prefer to inline the function, you could structure it in the following manner:

for(var i=0; i<5; i++){
    (function (i, xhr) {
        xhr.open("GET","d.php?id=" + i);
        xhr.send(null);
        xhr.onreadystatechange=function(){
            if (xhr.readyState == 4 && xhr.status == 200)
                alert(i);
        }
    }(i, new XMLHttpRequest()));
} 

Answer №2

This occurs because the closure stores not only the present value of the variable i, but also the variable itself. If I were in this situation, I would likely implement a solution like this:

for(var i = 0; i < 5; i ++) (function(i) {
        [..] console.log(i) [..]
})(i);

Answer №3

Just revising the code to align with your requirements

for (let i = 0; i < 5; i++) {
    let x = new XMLHttpRequest();
    x.open("GET", "d.php?id=" + i);
    x.send(null);
    x.onreadystatechange = (function(i, x) {
        return function () {
            if (x.readyState == 4 && x.status == 200) alert(i);
       }
    })(i, x)
}

Hopefully this modification is helpful

The code has been adjusted for x, so it should now function correctly

Answer №4

Here is my solution:

let x = new Array();
for (let i = 0; i < 5; i++) {
    x[i] = new XMLHttpRequest();
    x[i].open("GET", "d.php?id=" + i);
    x[i].send(null);
    x[i].onreadystatechange = (function(index) {
        return function() {
            if (x[index].readyState == 4 && x[index].status == 404) {
                alert(index);
            }
        }
    })(i);
}

However, I am intrigued by the idea of using closures to solve this problem. Can anyone provide guidance on how to utilize closures for a better solution?

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

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

I'm attempting to create a button using html, but I'm puzzled as to why it's not functioning as expected

I've been working on creating a button that, when pressed, generates a new div string based on the node.innerHTML code. For some reason, my code doesn't seem to be functioning properly and I'm not sure why. Here's the HTML: <input ...

Mapping a list of keys to Firebase objects in Vue.js

I am currently working on a compact web application using Vue.js and Firebase for data storage and synchronization. The app consists of storing 'items' with attributes like 'title' and 'subtitle', and 'lists' with an ...

Tips for managing serverside validation and clientside validation in your web application

Utilizing both clientside and serverside validation in ASP.NET controls is crucial for ensuring usability and security. While simple validations like length checks or regular expressions are easy to implement and maintain, more complex validations can beco ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

Using JavaScript to Detect Asynchronous Postbacks in ASP.NET AJAX

Seeking advice on the JavaScript code required to determine if an asynchronous postback is in progress. Can anyone help with this? Appreciate any assistance. ...

The image fails to load after I moved the routers from the server file (entry point file) to the controller file

I recently made the decision to transition two routers from my server file to my controller file in order to adhere to the MVC format. However, after making this change, I realized that the logo image is no longer visible on those routers. It seems like al ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

Dropdown selection values were not set appropriately

I've been encountering an issue with setting the selected value in a drop-down list using the code below. The values are being split from a comma-separated string, but it's not functioning as intended. When I use string='text1,text2,text3,t ...

Develop a Modal Form using Bootstrap (HTML)

I followed a tutorial on creating a modal form with Bootstrap, you can find it here: http://www.youtube.com/watch?v=HCEbp07hfLw I replicated the steps shown in the video, but when I try to open the page in my browser, nothing appears. I have added the Bo ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Adding a fresh HTML element to a list at a designated location

I found this excellent example on CODEPEN Is there a way to insert a new random number into the list so that it appears after 24 but before 19? Is there an efficient solution or do I need to manually check each li element and determine where to place the ...

Initiate an Ajax request from a hyperlink

Is it possible to trigger an Ajax request from a hyperlink? I am interested in updating the inner html of a div element upon clicking on a hyperlink through JavaScript. ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Setting a scope variable in an isolate scope from a link function can be achieved by accessing the

In my attempt to assign a variable within an isolate scope, I am encountering difficulties accessing the variable set in the linked function. Surprisingly, I can access the controller's variable without any issues. app.directive('myDir', fu ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...