JavaScript - asynchronous XMLHttpRequest with increment operation

Hello, it's my debut on SO, although I've been a regular user for quite some time and found all the answers I needed here...until now.

I'm currently grappling with an intricate issue involving XHR. While I consider myself a bit of a JS newbie, I never anticipated facing this particular challenge and I'm struggling to overcome it...

The crux of the matter is that I'm fetching a series of images from a remote server using a "for" loop. This part is functioning smoothly. However, I aim to assign them unique IDs to be able to manipulate them sequentially in a canvas for animation purposes. The problem arises with incrementing the ID properly. Here's a snippet of my code :


<body>

<button onclick="loadCanvas(113);">Click here</button>
<canvas id="targetedCanvas" width="768" height="512"></canvas>
<script>
    window.URL = window.URL || window.webkitURL;        

    function loadImages() {
        for (id = 0; id < 114; id++) {
            var url = 'http://myurl.com/IMG_'+id+'.JPG';
            var request = new XMLHttpRequest();
            request.open('GET', url, true);
            request.responseType = 'blob';
            request.onload = function(e) {
                if(this.status == 200) {
                    var blob = this.response;

                    var img = document.createElement('img');
                    img.id = id;
                    img.onload = function(e) {
                        window.URL.revokeObjectURL(img.src);
                    };
                    img.src = window.URL.createObjectURL(blob);
                    img.width = 0;
                    img.height = 0;
                    document.body.appendChild(img);
                }
            }
            request.send(null);
        };
    }

    function loadCanvas(id) {
        var canvas = document.getElementById('targetedCanvas');
        var context = canvas.getContext('2d');
        var img = document.getElementById(id);
        context.drawImage(img,0,0);
    };

    loadImages();

</script>
</body>

As you can observe, there's a button that loads the image onto the canvas upon clicking. When attempting to display the ID (console.log(id);), it functions correctly outside the request.onload function (i.e., increments as expected like 1, 2, 3...). However, inside the function, it stays fixed at 113. This discrepancy baffles me. I presume it has something to do with XHR being asynchronous or similar complexities – areas where my understanding is limited.

If anyone possesses insights or solutions to circumvent this hurdle and utilize the XHR-fetched images differently, I'd greatly appreciate your input! :)

A heartfelt thank you to the SO community!

Answer №1

Using a self-invoking function is essential here, as it allows you to pass the specific ID within that function.

Since the requests are asynchronous by nature, there's a risk of the for loop completing before any responses are received. This can result in all IDs being assigned as 114. To avoid this issue, ensure proper preservation using a self-invoking function.

function loadImages() {
    for (id = 0; id < 114; id++) {
        (function(id){
            var url = 'http://myurl.com/IMG_'+id+'.JPG';
            var request = new XMLHttpRequest();
            request.open('GET', url, true);
            request.responseType = 'blob';
            request.onload = function(e) {
                if(this.status == 200) {
                    var blob = this.response;

                    var img = document.createElement('img');
                    img.id = id;
                    img.onload = function(e) {
                        window.URL.revokeObjectURL(img.src);
                    };
                    img.src = window.URL.createObjectURL(blob);
                    img.width = 0;
                    img.height = 0;
                    document.body.appendChild(img);
                }
            }
            request.send(null);
        })(id);
    };
}

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

assign a variable a value within a function and then retrieve it externally

In order to validate a simple form, I am reading a JSON file and extracting an array from it. My goal is to check if this array contains every single element from a user-generated array, and nothing more. For instance: [1,2,3,4,5] (JSON file array) [1,2,3 ...

Converting JavaScript JSON into a PHP array

When working with Javascript, I create an array using the following code: cachePHP = "'lat':'" + (Number(upDataItems[2])).toFixed(5)+"'"; cachePHP = cachePHP + ",'lon':'" + (Number(upDataItems[3])).toFixed(5)+"' ...

I'm debating between using an AJAX form and sticking with a PHP-only form, and my main worry is ensuring

I am currently working on a PHP-driven website that includes a form for recordkeeping. The user selects a battle from the first dropdown, followed by choosing the winning side from the second dropdown. At present, the options for the winning side are limit ...

Can you please provide instructions on how to expand the view in the title bar for a JavaScript/CSS/HTML UPW project?

Struggling to integrate the title bar in a UWP project using JavaScript/CSS/HTML and having trouble accessing the necessary APIs. Came across a custom helper class written in c++ in UWP samples on Github, but unable to reference it in my javascript code. H ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Web-based client services

Context: An HTML file I'm working with takes in multiple parameters and utilizes JavaScript to dynamically render the content. The page pulls data from various local XML files for processing. For instance, accessing service.html?ID=123 displays info ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Exploring Nuxt.js internationalization (i18n) features: A step-by-step guide

I recently came across an example of internationalization (i18n) in the Nuxt.Js documentation. While I understand most of it, I am curious about how clicking on the Language option in the Navbar menu can switch the locale from 'en' to 'fr&ap ...

Using AJAX to Interact with PHP

Currently, I am facing a problem with my PHP code where my For each loop is not properly waiting for the response of the AJAX call. I have attempted to incorporate Promise functions to solve this issue but unfortunately, it did not work out as expected. ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Enumerate the variable values that are validated using jQuery

I've made good progress with this in jsFiddle, but I can't seem to figure out why the first value isn't displaying a bullet point.. Check out my code on jsFiddle! <div id="checkboxes"> <input id="chkbx_0" type="checkbox" name= ...

The JQuery script is not producing any results

After integrating a script into my website template, it is not functioning as expected. I suspect there may be a conflict with JavaScript, but upon inspecting with firebug, I am unable to identify any abnormalities. Here is the link for reference: Link ...

Error encountered during installation of Webpack and webpack-dev-server

I'm currently working on setting up Webpack and Babel for utilizing React without Create React App (CRA). While trying to install webpack-dev-server, I encountered some dependency issues. PS C:\Users\Lebedev\Desktop\projects\ ...

Leveraging JQuery animation to manipulate the spinning of HTML jackpot

I have been using the following code to simulate a spinning wheel for users. It is functional, but I am facing an issue where the rotation stops abruptly at a specific circle before applying the style for the winning circle. My query is: Is there any way ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

What is the best way to reset an HTML file input using JavaScript?

Looking for a way to reset the file input in my form. I've tried setting the sources to the same method, but it doesn't delete the selected file path. Important: Trying to find a solution without having to reload the page, reset the form, or us ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

Need a jQuery function that updates the 'id' after clicking on a specific div? Here's how to do it!

I need help simplifying my current situation. Step 1: I want to increment the variable "count" by 1 every time a specific div is clicked. Step 2: After updating "count", I want to utilize it in another function. This function involves copying the value f ...

Validation on the client side for a form that is displayed within a bootstrap modal using ajax technology

Within my ASP.Net Core application, I am faced with the need to utilize validation on both the server side and client side in a bootstrap modal form. While I have successfully implemented server side validation, I have encountered difficulties when it come ...