0

I'm trying to create a code that will check a list of URLs if available or not but my problem is that it only returns the last link inside a loop.

below is my code:

$('#dlink').click(function(e) {
    e.preventDefault();
    var dcode = $('#dnum').text();
    var dtemp = 0;
    for(dtemp = 1; dtemp <= 10; dtemp++) {
      var dlink = 'http://sample.com/export_template' + dtemp + '?field_delivery_code_value=' + dcode;
      $.ajax(
      {
        type: 'GET',
        cache: 'FALSE',
        url: dlink,
        success: function(response) {
          window.open(dlink);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.debug("error for " + dtemp);
        console.log(XMLHttpRequest);
        }
      });
    }
});
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
user3913971
  • 13
  • 1
  • 4

2 Answers2

0

Here's a function that will help you to do that and you don't need jQuery.

var is200 = function (url, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', url, false)
  request.onreadystatechange = function () {
      // At ready state 2, headers are received and status code by extension
      if( request.readyState == 2)
        return callback(request.statusCode == 200);          
      }
  };
  request.open(null);
};

The callback function will have one argument: a boolean of the equality of the status code with the number 200.

gaelgillard
  • 2,483
  • 1
  • 14
  • 20
0

You use a callback inside a loop and passes a variable to it which is updated inside the loop. So when the callbacks are called it , the updated variable will use the last state for all callbacks! see this thread for more info: When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback?

Community
  • 1
  • 1
David P.
  • 370
  • 1
  • 13