Javascript image load: get error status

4.3k Views Asked by At

I am loading a image trough javascript:

myimage.src = "/mycontroller/mymethod";
myimage.alt = "image";
myimage.onload = function(){
    $('body').append(myimage);
};    

But, somethimes my controller method should return an error, with the http status 500. So, the content-type will not be image/png anymore. Will be text.
There's a way to identify this error when loading the image, get the error message and display an alert?

2

There are 2 best solutions below

1
On BEST ANSWER

If the method is not guaranteed to succeed, a better solution would be for your method to return Javascript code which either loads an image, or displays an error. As far as I know, there is no way to tell if a URL to an image is actually an image, or if it's text data. I would love it if someone else provides an answer that proves me wrong!

0
On

What you can do is use the onError event for the image to tell you if there is a valid image file.

For example:

Say you have a directory with 5 image files in it: img1.jpg, img2.jpg, img3.jpg, img4.jpg, and img5.jpg.

This is the code for your web page that changes the image displayed every time you click on the image:

[html]

<img id="image" onClick="changeImage();" onError="error();" src="img1.jpg" />

[javascript]

var number = 1;
function changeImage() 
{
number++;
document.getElementById("image").src = "img" + number + ".jpg";
}

function error()
{
alert("This image does not exist");
}

With this set up, when you click on the image for the fifth time, the image tag's onError event is triggered and you will call the function that displays the error message. Letting you know that the file, img6.jpg does not exist. Now, there are ways you can manipulate this event to explore local directories, but it is limited in some ways. It would be far more usefull if it was an actual attribute with a true/false value assigned to it so it could be used as a test condition.

Since it cant be used as a test condition, you have to wait until the page recognizes the error and reports it to your script, which messes things up when you have a time based script, like on that uses setInterval.

Hope this answer helps people who read this question in the future, since my answer is over a year late...