Tips for successfully sending an array via an XMLHttp Get request

I am currently working on a project where I need to utilize all the values from an array in my GET request. The code snippet below outlines my approach:

function executeRequest(){
    let data = ['value1', 'value2', 'value3'];
    let httpRequest;
     function makeRequest(){
      httpRequest = new XMLHttpRequest;
      httpRequest.onreadystatechange = data;
      for(var i = 0; i < data.length; i++){
      (function(i){
      httpRequest.open('GET', 'https://example.com/' + data[i] , true);
      })()}
      httpRequest.send();
   }
}

Despite setting this up, I keep receiving undefined values for data[i]. I'm unsure if I am handling arrays correctly with the httpRequest. Any guidance on how to resolve this issue would be greatly appreciated.

Answer №1

If you want to proceed in the same manner, you'll need to generate a for loop similar to the one below:

for(var i = 0; i < test.length; i++){    
    sendHttpRequest(test[i])

Each item will require its own request. Alternatively, consider modifying your API to support accepting an array of values and providing data for them.

Answer №2

When test[i] returns undefined, it is likely because the parameter i is not being passed in properly within the code. The error is occurring due to an issue with the Immediately Invoked Function Expression (IIFE):

function something() {
  let test = ['something', 'other', 'test'];
  let httpRequest;

  function makeRequest() {
    httpRequest = new XMLHttpRequest;
    httpRequest.onreadystatechange = test;
    for (var i = 0; i < test.length; i++) {
      (function(i) {
        console.log(test[i]);
        httpRequest.open('GET', 'https://test.com/' + test[i], true);
         httpRequest.send(); // send request within loop
      })(i); // pass i here
    }
    // httpRequest.send();
  }
  
  makeRequest(); // call for testing
}

something(); // call for testing

Additionally, there are some issues within the code that need to be addressed:

  1. If multiple calls are intended, the request should be sent within the loop by using httpRequest.send()

  2. The onreadystatechange property should specify a function, assigning an array does not serve any purpose

  3. To handle simultaneous requests, you will need to create separate instances of XMLHttpRequest. Currently, only one instance is being created and reused which may lead to aborted requests.

For more detailed insights, visit this link.

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

Transition from mouse wheel scroll to page scroll not functioning properly when overflow is enabled

The website has a fixed element that uses overflow:auto. Users can scroll this element by positioning the mouse over it. However, once the element reaches the end of its scroll, the page does not seamlessly take over the scrolling. Instead, there is about ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

I require the capability to retrieve JSON data from beyond the confines of the function

After searching, I was unable to locate it. In my possession is a javascript file and a separate file named data.json. data.json { "today": [ { "id": 1, "title": "Note 1", "date": "21.05.2019", "text": "Lorem ipsum dolor sit ...

Steps for adding a div after a specified number

To display the following div after getting a value greater than or equal to the specified value and retrieving it through ajax: 1. How can I show the below div with the given value? .mainbox{ width:auto; height:auto; padding:20px; background:#f00; } .i ...

What is the reason for the maximum alias number in the npm YAML library?

I have been utilizing the npm module yaml to convert complex, interdependent JavaScript objects into a text format that can be easily restored in Javascript. Additionally, I use this package for deep copying of deeply nested objects by serializing and then ...

Fatal error encountered in Vscode while running the debug console

Every time I attempt to console log any code, I consistently encounter this error: ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

I'm having trouble setting up the REST API Sinch with PHP, can anyone help me out?

Just starting to explore cURL in PHP, I wanted to try using it with an API for sending SMS. However, every test I run results in the error message below: HTTP/1.1 400 Bad Request Content-Length: 0 X-Application-Context: application:production:8080 I&ap ...

Cannot find a function within the Promise

Here is the code snippet I am working with: var c = function(address, abiJson){ var _ = this; this.data = { wallet: false, account:{ address: false }, contract:{ addre ...

What is the best way to handle '<%=>' syntax in grunt?

Many grunt plugins support the following syntax for including files: ['<%= src_dir %>/common/**/*.js', '<%= src_dir %>/app/**/*.js'] or ['<%= test_files.js %>'] Is there a way to utilize a library that ca ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

Unable to access remote video streams by directly modifying URL parameters

Recently, I delved into experimenting with the straightforward mediasoup demo available at: https://github.com/Dirvann/mediasoup-sfu-webrtc-video-rooms After setting up the demo, everything seemed to be functioning correctly. The initial task on my agend ...

A label in nativescript not displaying a two-digit number

I've encountered a peculiar issue with my user interface. I have a barcode scanner on my phone that scans barcodes and stores them in an observable array (which is functioning correctly). I also have a label that displays the length of the array. When ...

What is the method to create a resizable table column border rather than resizing the bottom corner border?

At the moment, we are able to resize the table border when we drag the corner. However, my goal is to enable resizing on the right side of the full border. Below is the CSS code for resizing: th{ resize: horizontal; overflow: auto; min-width: 100px! ...

jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a ...

Having difficulty uploading a file using a formGroup

Currently, I am using Angular to create a registration form that includes information such as name, email, password, and avatar. For the backend, I am utilizing NodeJS and MongoDB to store this information. I have successfully written the registration API ...

What is the best way to showcase Vue data of a selected element from a v-for loop in a

Here is an example of how my json data is structured. I have multiple elements being displayed in a v-for loop, and when one is clicked, I want to show specific information from that element in a modal. [{ "id": 1, "companyNa ...