Using XMLHttpRequest within a loop

The current code is designed to iterate through multiple webpages, extracting all the links on each page and listing them in the console. However, it appears that only the links from the last webpage (fakeURL.com/735) are being displayed.

Is there a way to make console.log(url); work during every iteration, instead of just the final one (when i=735)?

for(i = 0; i <= 735; i += 15) 
{
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (xhrs.readyState == 4) 
        {
            $(xhrs.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
        xhrs.send();
}

Answer №1

The main issue you are facing here is the reuse of the same variable xhrs for all your ajax calls. This leads to confusion as each call cannot find its specific xhrs variable when the onreadystatechange event triggers. Consequently, they end up accessing the xhrs.readyState from the last request, resulting in only the final request being completed.

To resolve this issue, you can utilize the keyword this to reference the request that triggered the onreadystatechange event:

for(i = 0; i <= 735; i += 15) {
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (this.readyState == 4) 
        {
            $(this.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
    xhrs.send();
}

If you are using jQuery, it might be simpler to switch to jQuery.ajax() instead, as suggested by others.

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

Challenges with the ASP .Net Core 3.1 octokit rest npm package

I am utilizing npm along with a gulpfile.js to export npm packages to a 'lib' folder under 'wwwroot'. This process works smoothly, and whenever I update a specific npm package listed in my gulpfile.js, it automatically pushes the conten ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Utilizing JavaScript to trigger an alert message upon selecting various options and blocking the onclick event

Setting up a simpleCart(js) with selectable options presents a challenge. The task at hand is to display an alert if not all drop-downs meet specific requirements and to prevent the "Add to cart" button from adding items to the cart when these conditions a ...

Retrieve content using Ajax request

Hey there, I've been tinkering with pure javascript to dynamically load content using AJAX without having to reload the entire page. document.getElementById('dashboard').addEventListener('click', dashboard); function dashboard(){ ...

How can you merge an array having similar keys in React?

i am facing an issue with my current output: [ { GolonganName: '3B - Niaga Besar', data: [ 172000 ] }, { GolonganName: '3A - Niaga Kecil', data: [ 76700 ] }, { GolonganName: '2B - Rumah Tangga Menengah', data: [ 57000 ] ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...

Position text beneath a collection of visuals

I've been working on a page layout where I have a menu with images aligned in a ul. However, when I try to add text under each image, the text ends up misaligned all the way to the right of the menu. I'm considering starting from scratch without ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Error: jquery unexpectedly encountered a token 'if'

I've successfully created an autocomplete suggestion box, but I'm facing an issue when using if and else along with console.log(). An error is displayed in my console saying Uncaught SyntaxError: Unexpected token if, and I'm not sure why. Ho ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Does anyone have a solution for resetting the ID numbers in a flatlist after removing an item from it?

As the title suggests, I am facing an issue with the following scenario: { id: '1', name: 'one' }, { id: '2', name: 'two' }, { id: '3', name: 'three' }, { id: '4', name: &apo ...

The functionality of Node async/await appears to be malfunctioning

In an effort to streamline my code and reduce the number of callbacks, I decided to explore using async/await. However, I encountered a problem where Express renders the view before the query is complete. The query results are correct, but they come after ...

Transforming Data into Columns with ES6 and TypeScript Using Index Signatures

Seeking a solution to transform/pivot the given data structure: const dataReceived: IOrder[] = [ {customerName: 'Customer 1', customerId: '1',auctionName: 'Auction 1', auctionId: '1', statusName: 'Awaiting&a ...

Is it possible for the upload form submission to wait until the file processing is finished?

Is it possible for the form submission to wait until the file processing is complete? I am currently using web2py and its sqlform to upload a video file. As the file is being uploaded, it is also being converted to flv format. The progress of both uploadi ...

Issues encountered when implementing server-sent events in a project built with Node.js and React

I've been working on implementing server-sent-events into my Node.js and React application. After doing some research and following tutorials online, I found this particular site to be very helpful and straightforward. The main objective is to have a ...

Issues with grunt - Alert: Task "ngAnnotate:dist" has encountered an error. Proceed using --force option

Encountering an unexpected issue with a Grunt task that previously ran smoothly. The error message is as follows: Running "ngAnnotate:dist" (ngAnnotate) task Generating ".tmp/concat/scripts/scripts.js" from: ".tmp/concat/scripts/scripts.js"...ERROR >& ...

Raycasting in Three.js towards the vector perpendicular to the left or right of the origin

I am attempting to cast a ray directly towards the left and right from a central point. The central vector I am using is the origin. In Three.js, the raycaster requires a direction as a parameter. var origin = new THREE.Vector3(); var direction = new TH ...

Developed PHP script to dynamically generate a select tag using AJAX

Hello, I have here the code for my index page <!DOCTYPE html> <html> <body> <script> function show_month(var) { if (windows.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Methods for reducing arrays in JavaScript

Is there a way to transform an array of objects into an object with one of the properties as a key? What is the best method to achieve this conversion? const data = [ { id: "first", name: "Product 1", type: "selecti ...