Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if image exists with given url?

Tags:

jquery

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

like image 342
X10nD Avatar asked Aug 01 '10 10:08

X10nD


People also ask

How do you check if a URL is an image?

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.

How can check image exist or not in URL in PHP?

php function url_exists($url) { if (! $fp = curl_init($url)) return false; return true; } ?>


Video Answer


2 Answers

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:

  • http://www.jibbering.com/2002/4/httprequest.html
  • http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/

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  } 
like image 65
Sarfraz Avatar answered Sep 23 '22 13:09

Sarfraz


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

like image 40
Helmut Avatar answered Sep 23 '22 13:09

Helmut