0
var selector = ''; 
$.each(data, function(key, val) {
  var img = '/wp-content/img/history/' + val.image_id + '.jpg';
  selector = '#img'+(key+1);
  $(selector).prepend('<img id src=' + img + ' alt="pic" />'); 
});

The above code snippet works, the images are loaded into the elements #img1, #img2, #img3, #img4. I cannot be sure the images exist so a .done/.fail was added to the file get.

var selector = '';
$.each(data, function(key, val) {
  var img = '/wp-content/img/history/' + val.image_id + '.jpg';
  selector = '#img' + (key + 1);
  $(selector).removeClass('d-none');
  
  $.get(img).done(function() {
    $(selector).empty();
    $(selector).prepend('<img id src=' + img + ' alt="pic" />');
  }).fail(function() {
    alert(val.image_id + ' not found');
  });
});

After done/.fail on the file get are added 'key' is no longer being incremented. Using a counter within the loop behaves the same way as 'Key'.

Does anyone have an insight as to the cause?

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • The difference is because the `$.get()` call in the second example is asynchronous. This means that the logic in `done()`/`fail()` occurs ***long*** after the `$.each()` loop has completed. Therefore the `selector` value will only ever be what it was set to in the *final* iteration of the loop. The quick way to fix this is to use a closure. The best practice way to fix this is to stop making AJAX requests in a loop.... – Rory McCrossan Apr 29 '21 at 15:25
  • ... ***However*** from the context of the code it looks like you're simply trying to perform an action depending on whether the `img` loads or not. In which case use a `load` and `error` event handler on the `img` elements (something like [this](https://stackoverflow.com/a/3877079/519413)) instead of AJAX. Better still, sanitise the input data and/or change the process logic so that there cannot possibly be any dead image links in the logic. – Rory McCrossan Apr 29 '21 at 15:27
  • Maybe this post will help you: https://stackoverflow.com/questions/3237553/jquery-ajax-call-within-an-each-loop – Bernhard Beatus Apr 29 '21 at 15:42

0 Answers0