0

I have an array that I want to using each value from it in my GET request. Something like this :

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){
      httpRequest.open('GET', 'https://test.com/' + test[i] , true);
      })()}
      httpeRequest.send();
   }
}

I keep getting undefined for test[i] though, and I'm not sure if this is how to correctly pass arrays through an httpRequest either. I will appreciate any help with this.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
meeenemk
  • 1
  • 2

2 Answers2

0

The way you are doing it you would have to create a for loop like this:

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

You have to create a new request for each item. Otherwise you could change your API to handle taking in an array of values and returning the data for them.

Jared
  • 100
  • 8
  • This works, but sometimes I get undefined, and when it does work I get my response objects in a json array, but I get two of the same objects for the last item in my array from my GET request and the error 'SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data ' – meeenemk Jan 15 '18 at 21:18
0

You are getting undefined for test[i] because you are not passing the parameter i, whereas you are expecting it as an argument in the 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

Other thing, there are some flaws in the code, like:

  1. You might need to send the request httpRequest.send() within the loop if you want multiple calls

  2. onreadystatechange should define a function; assigning an array doesn't make sense

  3. For simultaneous calls, you might have to create multiple XMLHttpRequest request. Right now you are only creating one and changing the url, these will just get aborted.

Checkout more detailed answer here.

n4m31ess_c0d3r
  • 3,028
  • 5
  • 26
  • 35