Sunday 14 January 2018

How to check image exist on server using JQuery Ajax

Sometimes you need to check whether resource is available on the server or not to show it on web page. For instance if you want to show image on your web page but you don't know whether it exists or not on server. How do you check that using Javascript or JQuery??

Well there is a way, using simple & small jquery/ajax code you can achieve that.

Here is the example:

 function IsImageExists(imageUrl){
  var result;  
  $.ajax({
       url: imageUrl,
       type:'HEAD',
       async: false,
       success: function(res){
        result=true;        
       },
       error:function(error){
        result=false;        
       }
  });
  return result;
 }
 
 var url="http://localhost:8080/myproject/images/myimg.png";
 var result=IsImageExists(url); 
 
 if(result == true){
  console.log("Image Exists");  
 }else{
  console.log("Image Not found");
 }

Hope it works. Thanks..!!