0

I am attempting to work out whether an image exists in javascript using the code below:

var image_url = 'http://www.tester.co.uk/shop/images/product_thumbs/t_' + prod.images.toLowerCase() + '.jpg';

        $.ajax({
            url: image_url,
            type:'HEAD',
            error:
            function(msg_no){
                console.log("fail."); 
                markup += "<td class='movie-image'><img src='/shop/html_templates/files/images/default-category-image.gif'/></td>";
            },
            success:
            function(msg_yes){
                console.log("success."); 
                markup +=  "<td class='movie-image'><img src='/shop/images/product_thumbs/t_" + prod.images.toLowerCase() + ".jpg'/></td>";
            }
        });

On the 404 pages my console log shows the fail message, however on the pages returning 200 I am not getting the success message.

I'm hoping someone can advise me on where I'm going wrong!

Thanks

hlh3406
  • 1,382
  • 5
  • 29
  • 46
  • Surely if the file does not exist and the server returns `200`, it is the server that is doing it wrong – Paul S. Jul 18 '13 at 14:45
  • Hi, no the image isn't cross domain. – hlh3406 Jul 18 '13 at 14:48
  • Hi, it's for a search facility so it returns multiple requests in one go, then it shows a 404 for the images that don't exist and can't be displayed - and in the console it displays the message I've put above - "fail" - but then if the image does exist it displays a 200 but doesn't enter my success function and display the console.log(success) – hlh3406 Jul 18 '13 at 14:49
  • similar stackoverflow question http://stackoverflow.com/questions/16553174/test-if-a-file-exists-with-javascript – Parag Nov 06 '13 at 05:45

1 Answers1

3

By looking at what you are actually doing, it might be wiser for you to not do this by ajax and instead rely on Image, which will throw an error if the returned data is not an (understood by browser) image, too.

var img = new Image();
img.onerror = function (msg_no) {
    console.log("fail."); 
    markup += "<td class='movie-image'><img src='/shop/html_templates/files/images/default-category-image.gif'/></td>";
}
img.onload = function (msg_yes) {
    console.log("success."); 
    markup +=  "<td class='movie-image'><img src='/shop/images/product_thumbs/t_" + prod.images.toLowerCase() + ".jpg'/></td>";
}
img.src = image_url; // fetch after listeners attached
Paul S.
  • 64,864
  • 9
  • 122
  • 138