I want to check if an image exists using jquery.
For example how do I check this image exists
http://www.google.com/images/srpr/nav_logo14.png
the check must give me a 200 or status ok
--------------edited-------------------
var imgsrc = $(this).attr('src'); var imgcheck = imgsrc.width; if (imgcheck==0) { alert("You have a zero size image"); } else { //do rest of code }
Thanks Jean
To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.
php function url_exists($url) { if (! $fp = curl_init($url)) return false; return true; } ?>
Use the error
handler like this:
$('#image_id').error(function() { alert('Image does not exist !!'); });
If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:
Update:
I think using:
$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});
would be enough to check for a 404.
More Readings:
Update 2:
Your code should be like this:
$(this).error(function() { alert('Image does not exist !!'); });
No need for these lines and that won't check if the remote file exists anyway:
var imgcheck = imgsrc.width; if (imgcheck==0) { alert("You have a zero size image"); } else { //execute the rest of code here }
$.ajax({ url:'http://www.example.com/somefile.ext', type:'HEAD', error: function(){ //do something depressing }, success: function(){ //do something cheerful :) } });
from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With