views:

491

answers:

3

Hi there

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?

+3  A: 

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.

JGB146
+1 Good thinking.
Gert G
-1 the `.load()` the OP is using is not an ajax.... http://api.jquery.com/load-event/
Reigel
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
I was so judging,.. +1... but then I will not take my -1 for you could just check it on client-side....
Reigel
@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.
JGB146
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.
JGB146
+2  A: 

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

like this,

$(".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...

Reigel
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
please explain why the down-vote. So that this answer could be improved if you have something...
Reigel
Not sure who downvoted you have +1 from me.
Marko