views:

44

answers:

3

I have an image like: img src="" class='listPartialLoader' alt='loading' I am assigning the 'src' value with data from an ajax call. Some times if the image is not found I want to add a default image path like"Images/default.jpg". But how can I check whether the image is exist or not using javascript? (Basically I want if the image is not found add a default image)

+1  A: 

if the image is in the same domain of your script just take the image path (before assign it to image element) and make a simple HEAD ajax request to that path (eg. "images/default.jpg) . If server status is 304 or 200, the image exists

Fabrizio Calderan
+1  A: 

You should be able to check if the image exists with the onerror and onload events.

var myImg = new Image;
myImg.src = 'path/to/image';

myImg.onerror = function(){
    console.log("Error!");
}

myImg.onload = function(){
    console.log('Loaded!');
}
Yi Jiang
+1  A: 

While you are retrieving the value for src property during the ajax call to the server, why not check if the file exists?

string src = GetSrc(); //whatever you need to do

if(System.IO.File.Exists(HttpContext.Current.Server.MapPath(src)))
{
    return src;
}
else
{
    return "path/default.jpg");
}
HectorMac