views:

50

answers:

2

I am using JQuery to dynamically add a link for an image file.

+ "<td><a class='IconButton' id='trkimg" + k + "' href='IMSTORE\/" + trackings[k].Image + "'><span class='ui-icon ui-icon-image'></span></td>"

This code checks that a value was returned from the database and hides the link if nothing was returned:

if (trackings[k].Image == null) { $("#trkimg" + k).html(""); $("#trkimg" + k).removeClass('CustomButton'); }

How can I use JQuery to validate that the file returned actually exists, and if it doesn't exist, display a different image?

+1  A: 

Javascript cannot see the files on your server. You could do an ajax request to something server side to check if the file exists I guess.

SeanJA
Is it possible to catch the 404 error and redirect to a different image?
wham12
A: 

Along the lines of what SeanJA suggested, you could use ajax to 'test' for the image, then actually append the image in the success callback, or try another in the error callback.

You're requesting the image twice, but maybe it is cached after the first try. Not sure.

If you want to actually use the image returned, it needs to be encoded. Here's a link to instructions on how to do it. Haven't tried it, though.

http://emilsblog.lerch.org/2009/07/javascript-hacks-using-xhr-to-load.html

    var imageURI = "http://mydomain.com/myimage.jpg";
    $.ajax(
        {
            type:'get',
            dataType:'image/jpeg',
            url:imageURI,
            success:function() { $('body').append('<img src="' + imageURI + '" />'); },
            error:function() { /* Change url in imageURI variable, and try again */ }
        }
    );

Not sure if this is the best way, but seems to work.

patrick dw