1

I'm trying to write code that loads multiple images with ajax once a thumbnail is clicked. The load method is wrapped in a for loop, since the images are named my-image-1, my-image-2 etc.. I would like to load the images by increasing i, and exit the loop once /my-image-i.jpg doesn't exist, yielding an error.

function load_slides(i) {
            console.log(i);
            var url = "some-url.jpg";
            var img = $('<img />').attr('src', url).load(function(response, status, xhr) {
                    if (status == "error") {
                        console.log("Error loading");
                        return false;
                    }
                });
        }
//code below is triggered upon clicking the thumbnail
for (var i = 1;; i++) {
                    if (!load_slides(i)) break;
                    else {
                        load_slides(i);
                    }
}

With the code above, I never see the error message and the loop never stops executing, when it shouldn't even start with a bad url :/

Thanks in advance for your help, I've been trying to figure this out for a while

Grey Vugrin
  • 455
  • 5
  • 12
  • Think about it... you fire off a call to fetch an image, milliseconds later you get the success/error status. By that time, load_slides will have already finished and the loop will have moved on. It is much better to determine valid filenames server-side. – DCoder Jun 24 '13 at 05:25
  • @DCoder Thanks for the quick response. I see your point, and I'm going to look in to determining the filenames on the server-side. Even if I knew the right names, how could I make the images load in a for loop, without having it do the same thing? – Grey Vugrin Jun 24 '13 at 05:36

1 Answers1

0

Updated

You can use this function for checking existence of a file like,

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status==404;
}


for (var i = 1;; i++) {
    // if UrlExists will return true then break, not found image
    url='my-image-'+i+'.jpg';
    if (UrlExists(url)) break;
    else {
       load_slides(i);//load image function calling
    }
}

Source from How do I check if file exists in jQuery or JavaScript?

Old

function load_slides(i) {
    console.log(i);
    var my_status=true;
    var url = "some-url.jpg";
    var img = $('<img />').attr('src', url).load(function(response, status, xhr) {
       if (status == "error") {
          console.log("Error loading");
          my_status=false;
       }
    });
    return my_status;// return mystatus from here to check;
}
//code below is triggered upon clicking the thumbnail
for (var i = 1;; i++) {
    // if my_status will return false then break
    if (!load_slides(i)) break;
    else {
       load_slides(i);
    }
}
Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106