What is the best way to send multiple XMLHttpRequests for JSON data from various sources?

I am attempting to make multiple XMLHttpRequests in JavaScript with two different URLs. My goal is to store each response in a variable and manipulate them all collectively.

Currently, this is how I am doing it. Is there a more graceful approach?

var firstRequest = new XMLHttpRequest();
firstRequest.open('GET', 'http://website-one.com/FIRST.json');
firstRequest.onload = function() {
    var dataOne = JSON.parse(firstRequest.responseText);
    callSecond(dataOne);
};
firstRequest.send();

function callSecond(dataFromOne) {
    var secondRequest = new XMLHttpRequest();
    secondRequest.open('GET', 'http://website-two.com/second.json');
    secondRequest.onload = function() {
        var dataTwo = JSON.parse(secondRequest.responseText);
        workTogether(dataFromOne, dataTwo);
};
secondRequest.send();

function workTogether(data1, data2) {
    //perform necessary operations
}

Answer №1

Unfortunately, there is no easier way to handle requests when using the XMLHtpRequest. Instead, you could opt for alternative libraries like Ajax or utilize newer JavaScript APIs such as Promises and async/await for more concise and readable code.

A refactored version of the code would look like this:

const chainedFunction = async () => {
   const firstResult = await ourRequest();
   const second = await call_second(firstResult);
   // perform additional tasks
};

Answer №2

There are several options available for handling this situation. You could utilize the Promise object along with Promise.all or opt for the simpler fetch method.

The Fetch API is designed to facilitate the retrieval of resources, including those obtained over a network connection.

If you choose to use the fetch approach, your code could resemble the following:

fetch('http://example.com/movies.json')
    .then(function(data_one) {
        fetch('http://example2.com/movies.json')
            .then(function(data_two) {
                function process_data(data_one, data_two)
            })
    })

Answer №3

Using Promise.all can streamline the process for you

const movieList = fetch('http://samplewebsite.com/movies.json')

const bookList = fetch('http://samplewebsite.com/books.json')


Promise
.all([movieList, bookList])
.then((response) =>  {

  console.log(response[0]); // movie data
  console.log(response[1]); // book data


});

Answer №4

A more refined approach is available. The main concept revolves around the principle of avoiding repetition.

function fetchData(url, callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function(event) {
    // XMLHttpRequest.DONE === 4
    if (this.readyState === XMLHttpRequest.DONE) {
      if (this.status === 200) {
        return callback(null, this.responseText);
      } else {
        return callback({errCode: this.status, errMsg: this.statusText});
      }
    }
  };

  xhr.open('GET', url, true);
  xhr.send(null);
}


fetchData('http://website-one.com/FIRST.json', function(errFirst, responseFirst) {
  if (errFirst) {
    throw new Error('An error occurred: ' + errFirst.errCode + '/' + errFirst.errMsg); 
  }
  return fetchData('http://website-two.com/second.json', function(errSecond, responseSecond) {
    if (errSecond) {
      throw new Error('An error occurred: ' + errSecond.errCode + '/' + errSecond.errMsg); 
    }
    return work_with_data(responseFirst, responseSecond);
  });
});

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

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Having trouble with Symfony and Doctrine returning a null response when querying the SQL database

How can I retrieve information from my MySql database using a query? The response I'm receiving is not what I expected. I have a table named message with a column called messageBody that I need to access. My goal is to fetch this data and return it ...

Encountered an issue accessing property 'Component' which is undefined during the webpack build of a React component plugin

I have developed a wrapper for my leaflet plugin called leaflet-arrowheads using react-leaflet. This component is designed to be installed as an npm package, imported, and used easily. The structure of the component is quite simple: import React from &apo ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Exploring the use of asynchronous data retrieval with jQuery and JSON within MVC 2.0

Attempting to retrieve server-side data using jQuery's getJSON method has hit a snag. The URL specified in the getJSON call is being reached, but the expected result is not being returned to the browser upon postback. There are suspicions that the iss ...

Text box size in user input not adapting on mobile devices

Website: Visit the Cutter Travel Calculator here I've encountered an issue with my user input text boxes on mobile. Despite setting their width using the formidable forms plugin, the size adjustment doesn't seem to apply when viewed on mobile de ...

Deciphering Complex JSON Strings with Java

I am facing a challenge with a complex String structure that resembles the following, "data":"[ { "id": "123456", "from": { "name": "ABC", "id": "123" }, "m ...

Exploring the concept of promise.reject() and the art of passing an object as a parameter

By passing response.json in Promise.reject(), I intended for it to be accessible in the catch block. However, it appears as undefined in the catch block. const checkResponse = (response) => { if (response.status >= 200 && response.status & ...

"Handling Errors in JavaScript when a Button Click Event Triggers a

There are 2 buttons intended for "Add to Favorites" and "Remove from Other Favorites". Here is the code snippet: <button type="submit" class="btn btn-warning btn-xs" id="FavoriButonex" data-id="<?php echo $sorid ?>"> <i class="fa fa-hea ...

Tips on setting an expiration time for verification codes in a Node.js environment

What is the best way to implement an expiration time for this verification code? I need it to be deleted from the database after 10 minutes. var fourcode = Math.floor(1000 + Math.random() * 9000); app.post("/sendforgetpassword", async (req, re ...

Retrieve the child property of an object directly without referencing the parent property

When using html2json, it returns an object with child objects. The challenge is to retrieve the value of the key "text", which can be located in different places depending on how many child objects there are. I have attempted the following code, but due t ...

The animation for the CSS gradient background is failing to animate

After finding a similar code snippet used for backgrounds, I made some modifications to suit my needs. However, when attempting to implement it or any animation, nothing seems to be working. Even simple animations are not functioning as expected. While I a ...

Unable to set height of images using jQuery following an ajax request

I have a function that determines the highest image height to set as the minimum height of the image container element, specifically a figure. Initially, the function works well on window load and when the window is resized. However, after an ajax call lo ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

What is the best way to obtain the id of an HTML element that is generated within jQuery code?

Typically, data is retrieved in HTML by storing the html in the html file. In my case, however, I create the html element inside jQuery. So, how do I call out the div id? How can I replace document.getElementByID ("edit").innerHTML=.... when the element i ...

Can the App be initiated manually using AngularJS and AJAX injection?

My current Angular application is loaded dynamically into the existing webpage. This means that all scripts (such as angular.min.js and controllers) are included in the Wicket AJAX request and injected into the webpage. The scripts are added to the head o ...

Is there a compatibility issue between Vue particles and my project?

Greetings to all! I recently added Vue Particle to my Vue project, but encountered an issue while importing VueParticles in the Main.js file. Here is a snapshot from my terminal for reference. https://i.stack.imgur.com/Bxh2r.png ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

Is there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...