I have a script that sends HTTP requests to a website to get documents, the document IDs are kept in an array. I want to send a request for each array element and return a message based on the status from the HEAD (e.g. 200 OK).

The problem I have is that when I loop through the URL array, multiple requests are sent using only the last array element, no other element is used.

Code:

//send http request
function sendRequest(url) {
  var newRequest = new XMLHttpRequest();

  newRequest.onreadystatechange = function() {
    if(newRequest.readyState == 4) {
      if(newRequest.status == 200) {    
        console.log("loaded: " + url);
      } else {
        console.log("Failed to load: " + url);
      }
    }
  }

  newRequest.open("HEAD", url);
  newRequest.send();
}

//send request for each url in array
for(var i = 0; i < urlArray.length; i++) {
  //get document id and append to link
  var address = "https://www.adsa.co.uk/library.dr/docs.aspx?id=" + 
                urlArray[i];
  //console.log(address + "\n");
  sendRequest(address);
}

Output (74 is the value of the last element in the array):
This console message is produced urlArray.length times:

Failed to load: https://www.adsa.co.uk/library.dr/docs.aspx?id=74

Any ideas why the sendRequest() is not sent for each array element?

share|improve this question
    
This fiddle: jsfiddle.net/y8k9wmkh seems to work fine. Can you change it to show your issue – Chris Charles 3 hours ago

Chrome (and Firefox) complains about invalid SSL certificate and therefore doesn’t connect:

Failed to load resource: net::ERR_INSECURE_RESPONSE
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.