Sending a request to multiple APIs using a GET method

Issue: I am facing a challenge with handling 47 URLs, each varying by their last one or two characters from 1 to 47.

For instance: https://example.com/api/data?number=1 <--- the number at the end ranges from 1 to 47

My objective is to retrieve data from each of these URLs through an API GET request in order to plot them.

Current Approach:

let urlBase = 'https://example.com/api/data?code='

let dataList = []

const xhr = new XMLHttpRequest()

for(let i=1; i<48; i++){
  xhr.open('GET', urlBase + i, true)
  xhr.send();

  xhr.onload = () => {
    let response = JSON.parse(xhr.responseText)
    dataList.push(response)
  }
}

Unfortunately, I am only getting the result for the last URL (#47) using this method.

If anyone has suggestions on how to successfully make these requests and save the response data into an array, I would greatly appreciate your input.

Thank you in advance,

Codey

Answer №1

One way to address this issue is by using a local variable within the for loop instead of overriding the request each time.

const baseURL = 'https://example.com/api/data?code='
let responseData = []

for(let count=1; count < 48; count++){
  let request = new XMLHttpRequest()
  request.open('GET', baseURL + count, true)
  request.send();

  request.onload = () => {
    let response = JSON.parse(request.responseText)
    responseData.push(response)
  }
}

Answer №2

It is expected that the last result is being returned because your code is written in Javascript. To resolve this issue, consider using an Async function. You can use a library like axios for making requests:

for(let j=1; j<50; j++){
sourceUrl = url +`&page_number=${j}`
async function fetchData() {
await axios.get(sourceUrl).then((response) => {
// Implement any desired actions here
}

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

`Weaving together and executing several animations using THREE.GLTFLoader in the world of three.js`

After exporting an animated model (spaceship) and an animated camera as a .glb file from Blender using the gltfExporter, I successfully viewed them in the glTF viewer (gltf-viewer.donmccurdy.com), confirming that the issue does not lie with the model or Bl ...

Managing numerous invocations of an asynchronous function

I have an imported component that triggers a function every time the user interacts with it, such as pressing a button. Within this function, I need to fetch data asynchronously. I want the function calls to run asynchronously, meaning each call will wait ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

Store in database and forward to a different web address

I have created an interactive quiz using jQuery. I need to add a specific feature at the end of the quiz. if (answered_questions === total_questions) { save the user's score to the database; redirect to specified URL; } The redirect_url is ...

Ajax-enabled pre-resize feature for efficient multiple file uploads

I'm currently facing an issue with a function that involves pre-resizing and ajax file uploading. I have a FOR loop which calls this function, depending on the length of the file input size. The strange thing is, sometimes when I call it multiple time ...

What is the method to create all possible combinations from the keys of a JSON object?

How can I generate object B that includes all combinations of object A using a key-value pair? { "x": "data-x", "y": "data-y", "z": "data-z" } The desired output should look like this: { ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Determine whether a specific key exists in the formdata object

Can I check if a key in the formdata object already has a value assigned to it? I am looking for a way to determine if a key has been previously assigned a value. I attempted something like this but did not get the desired outcome data = new FormData(); ...

Using JavaScript click event to send information to the database

I really need some guidance with JavaScript and ajax. I would appreciate any help on this topic. I am particularly interested in the question here: Updating a MySql database using PHP via an onClick javascript function Specifically, I am intrigued by th ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

Unable to send HTML content back from the controller when making Ajax requests in a messaging application

Currently, I am in the process of developing an integrated chat application within CRM. The main functionality involves displaying the chat history between users when a logged-in user clicks on a contact using Ajax calls. However, I have encountered some i ...

Encrypting and decrypting characters such as "é" using EncodeURIComponent and DecodeURIComponent functions

I am facing an issue with my web application that involves a drop-down list containing parameters with accents, such as: "Bonjour/COUCOU SPéCIALISTE/AB12345" When I select this parameter and perform a search, the resulting URL looks like this: abcdefgh. ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

What is the method for retrieving a specific value following the submission of an AngularJS form?

Here is how my form begins: <!-- form --> <form ng-submit="form.submit()" class="form-horizontal" role="form" style="margin-top: 15px;"> <div class="form-group"> <label for="inputUrl" class="col-sm- ...

Using Laravel: Validate username existence with jQuery AJAX before form submission

After creating a registration form with numerous fields, I encountered an issue when submitting data and receiving validation errors. The user would have to refill empty inputs, causing unnecessary delays. To streamline the process, I am looking to impleme ...

The function get() in p5.js will provide you with an array of pixels that is empty

I am currently working on a project that is inspired by this particular video. Within p5.js, I have been utilizing the get() function. My goal is to divide a large tileset into smaller images and store them in an array. However, I have encountered an issue ...