Use javascript to retrieve multiple images from the server using XMLHttpRequest

Currently, I am successfully using the XMLHttpRequest method to obtain the URL of a single image from the server in order to download, save, and retrieve it from Android local storage. However, I have hit a roadblock when attempting to figure out how to download multiple images from the server using the same method. Can anyone offer me some guidance or solutions?

Thank you in advance for any assistance!

Below is the code that I am utilizing to download a single image:

        var xhr = new XMLHttpRequest();

        xhr.open('GET', url, true);

        xhr.responseType = "blob";
        console.log(xhr);

        xhr.onload = function (e) {
            console.log(e);
            if (xhr.readyState == 4) {
                console.log(xhr.response);
                // if (success) success(xhr.response);
                saveFile(xhr.response, 'images');
            }
        };
        xhr.send();

Answer №1

If you have a list of URLs where images can be accessed, a straightforward approach is to create a for loop and save instances of the XMLHttpRequest variable in an array.

var xhrArray = [];
var urlArray = ['website.com/picture1',
               'website.com/picture2',
               'website.com/picture3'];
for (let i=0; i< urlArray.length; i++){
    xhrArray[i] = new XMLHttpRequest();

    xhrArray[i].open('GET', urlArray[i], true);

    xhrArray[i].responseType = "blob";
    console.log(xhrArray[i]);

    xhrArray[i].onload = function (e) {
        console.log(e);
        if (this.readyState == 4) {
            console.log(this.response);
            // if (success) success(this.response);
            saveFile(this.response, 'images');
        }
    };
    xhrArray[i].send();
}

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

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

Tips for saving a Cytoscape.js diagram as an image

Currently, I am diving into learning Cytoscape.js. After successfully creating an HTML file with a basic graph, I attempted to export the graph to an image using the following code: var png64 = cy.png(); // Inserting the png data in an img tag document.qu ...

Is it possible to trigger an AJAX validation only after the jQuery validation plugin has successfully validated the input?

I utilized the jQuery validation plugin for form field validation. The goal now is to send an ajax request only when the fields are deemed valid by the jQuery validation plugin. JavaScript: $(function(){ $("#form").validate({ errorPlacement: ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

Keep the multiselect dropdown list of the select component open

I am currently utilizing the Select component from material-ui-next. Overall, it functions quite smoothly. One scenario where I implement it is within a cell element of an Ag-Grid. Specifically, in this use case, I am making use of the multiselect feature ...

Troubleshooting Problems with Ajax across Different Web Browsers

I am facing an issue with my ajax function - it works perfectly on Chrome and Firefox, but not on Internet Explorer 8. Can anyone help me identify the problem? Here is the HTML section: <select id='choices'> <option id="no" value="no" ...

The clash of interests between jQuery and Bootstrap

I'm facing a problem with conflicting jQuery and Bootstrap files in my header.php code. Whenever I include the jQuery file before the bootstrap.js file, it causes issues with the tabs on my website where clicking on them does not navigate me to the co ...

Encountering issue: Unrecognized parameter "id" in the "user" field of type "Query" [GraphQL, Relay, React]

We are currently setting up a query in relay. Our user database is structured like this: function User(id, name, description) { this.id = id.toString() this.name = name this.description = description } var users = [new User(1, 'abc', &a ...

What is the best way to send a parameter to a component in Vue.js without including it in the URL during routing?

One of my Vue.js components is a SideBar that retrieves JSON data. The JSON data consists of names that correspond to specific URLs which in turn contain more JSON data. { "applicants": "url1", "applications": "url2" ...

The componentDidUpdate function fails to trigger in React Native after modifying the reference of its prop

In this section of my parent component, I am invoking my child component AttachmentField. configurableField.attachments.map((item, i) => { if (item.type.includes("pdf")) { const url ...

Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that? const EditController = () => { c ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

What is the most effective way to design a MongoDB query that can assess a permission hierarchy involving both allow and deny rules within my Access Control

Creating a per-document access control list (ACL) for an application using MongoDB comes with specific requirements: Each find or update query can be expanded with a crafted ACL query to determine if the operation is permitted, without increasing databas ...

What sets apart the usage of `import Anything from #anywhere` from not importing anything at all?

When utilizing the autoimport feature of Nuxt 3: Are there any implications (such as types, performance, bundle size, tree shaking, etc.) when using the # alias to import something as opposed to not importing at all? Or is its sole purpose to provide expl ...

Ensure that the click event is triggered only once for each distinct class

Is there a way to make a click event trigger on any element with the same class just once? I attempted using '.one', however, it removes itself after the first element with the class is clicked. $(document).ready(function() { $(".dro ...

React Array Number Looping

I am working with an array let counterArray = [5]; Currently, I need to iterate through the array 5 times {counterArray .map(counter=> <span>Counter- {counter}</span> )} Right now, this code snippet just displays the counter. How can ...

Identifying Words and converting them into Voice.. Such as R.. Then articulating R

I have an innovative idea for an application, but I am facing a roadblock. My concept involves being able to write any letter on an Android screen by using finger scrolling. Additionally, I would like the Android device to be able to read out loud what has ...

Types that depend on function input parameters

I am facing a challenge with a function: function navigateOptions(currentScreenRoute: 'addGroup' | 'addGroupOnboarding', group: GroupEngagement) { const navigationKey = currentScreenRoute === 'addGroup' ? 'addGroupPeopl ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Tips for utilizing a variable selector with jQuery's .attr() method

In a jQuery DataTable, there is a scenario where some values can be modified by clicking an edit button. When clicked, a modal popup appears with a form to enter new values for notes and status: ... "columnDefs": [ { ...