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?

3
  • 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.... Commented Apr 29, 2021 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) 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. Commented Apr 29, 2021 at 15:27
  • Maybe this post will help you: stackoverflow.com/questions/3237553/… Commented Apr 29, 2021 at 15:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.