23

I'm loading an image path via jQuery $.ajax and before showing the image I'd like to check if it in fact exists. Can I use the image load/ready event or something similar to determine that the file path is valid?

Having .myimage set to display: none, I'm hoping to do something like

$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
    $(this).show();
});

Is anything like that possible?

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
Marko
  • 71,361
  • 28
  • 124
  • 158
  • This might help http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06 – Hari Oct 18 '10 at 21:23

6 Answers6

34

Well, you can bind .error() handler...

Update: In jQuery 3.0 and later:

$(".myimage").on("error", function() {
    $(this).hide();
});

note: .error() was deprecated in jQuery 1.8 and removed in 3.0 but in in older versions you can:

$(".myimage").error(function(){
  $(this).hide();
});

well, yours is okay already with load-event

$(".myimage").load(function() {
    $(this).show();
});

the problem with this is if Javascript was disabled the image will not ever show...

vinnyjames
  • 2,040
  • 18
  • 26
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • Oh really? I didn't think the load method could be used, I just posted it as an example of what I'm trying to do. Also I'm not concerned about Javascript being disabled since I'm using $.ajax to start with.. :) +1 – Marko Jul 25 '10 at 01:50
  • please explain why the down-vote. So that this answer could be improved if you have something... – Reigel Gallarde Jul 25 '10 at 02:12
  • This seems to work only intermittently in Internet Explorer 9. (I haven't tested the other ie versions). I am using multiple $(document).ready functions but it seems to work without a hitch in the other browsers and no errors are being thrown. You can see it here - if a cover doesn't exist on the server, it means that it has been removed and then show the cover removed information. http://fordummiescovers.com/share.php?id=100 JS functionality: http://fordummiescovers.com/js/covercheck.js – BWelfel May 08 '11 at 23:31
22

Try:

function urlExists(testUrl) {
 var http = jQuery.ajax({
    type:"HEAD",
    url: testUrl,
    async: false
  })
  return http.status;
      // this will return 200 on success, and 0 or negative value on error
}

then use

if(urlExists('urlToImgOrAnything') == 200) {
    // success
}
else {
    // error
}
bzx
  • 1,364
  • 11
  • 10
Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
  • This results in the following warning: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience." – sanchez Mar 15 '15 at 11:53
7

An old thread I know but I think it could be improved. I noticed OP having intermittent problems which could be due to loading of the image and error checking simultaneously. It would be better to let the image load first and then check for errors:

$(".myimage").attr("src", imagePath).error(function() {
    // do something
});
superjaz1
  • 436
  • 4
  • 11
4

Since you're already doing an AJAX request, I would offload this to the server-side app that is supporting your AJAX. It's trivial to check to see if a file exists from the server, and you could set variables in the data you send back to specify results.

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
  • 1
    -1 the `.load()` the OP is using is not an ajax.... http://api.jquery.com/load-event/ – Reigel Gallarde Jul 25 '10 at 01:43
  • That's a decent answer and a possible alternative, but my question is if I can check with jQuery specifically.. +1 for the server method though. – Marko Jul 25 '10 at 01:47
  • I was so judging,.. +1... but then I will not take my -1 for you could just check it on client-side.... – Reigel Gallarde Jul 25 '10 at 01:50
  • @Reigel: OP specifically mentioned that he was using AJAX to get his data in the first place, when describing his process. Further, any method to check if the file exists is going to have to send another request to the server anyway - you're either doing it server-side once, or you're doing extra client-side work to only to still have interactions with the server as a result of anything you do. – Jeffrey Blake Jul 25 '10 at 03:19
  • 2
    To clarify the above, you're never just checking for files on the client-side. Any code to do so will send at least one, and possibly many additional requests to the server. So it's far better to send the info back in the original interaction with the server. – Jeffrey Blake Jul 25 '10 at 03:28
2

This question is a couple years old, but here's a better example usage for the error handler for anyone looking at this.

$("img")
  .error(function(){
    $(this).hide();
  })
  .attr("src", "image.png");

You need to attach the error handler before you try to load the image in order to catch the event.

Source: http://api.jquery.com/error/

Chris
  • 673
  • 1
  • 10
  • 28
0

This is what I did of mine:

$.get( 'url/image', function(res){ 
    //Sometimes has a redirect to not found url
    //Or just detect first the content result and get the a keyword for 'indexof'
    if ( res.indexOf( 'DOCTYPE' ) !== -1 )  {
        //not exists
    } else {
        //exists
    }
});
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
ruel
  • 1
  • 1