1

I need to load an image by Javascript, but know the difference between a 404 and 500 error if it fails.

I have code to load an image into an 'img' tag like the below:

var img = $('<img />').attr('src', url)
    .load(function() {
        // Do something.
    })
    .error(function(ev) {
        // What sort of error?
    });

In the error() function, I don't seem able to tell whether the error was a 500 or a 404. Is there any way of doing this?

3
  • I'm surprised that .error works at all! It shouldn't. Why does jQuery care that you setting the src attribute vs. any other attribute? How/why would it even be able to hook into the HTTP request for an element on the page? Commented Mar 24, 2013 at 17:00
  • It's documented functionality: api.jquery.com/error Commented Mar 25, 2013 at 8:54
  • Interesting! I had no idea. Commented Mar 25, 2013 at 13:12

1 Answer 1

1

Handle and test http status page like this

DEMO

var img = $('<img />')
    .load(function() {
        // Do something.
    })
    .error(function(jqXHR, error, errorThrown) {  
       if(jqXHR.status&&jqXHR.status==404)
       {
            alert(jqXHR.responseText); 
       }
       else
       {
           alert("Something went wrong");
       }
    })
    .attr('src', url);
Sign up to request clarification or add additional context in comments.

4 Comments

In Chrome, jqXHR.status seems always to be null. Therefore I seem always to get the 'Something went wrong' alert.
I don't experiment your problem. Here is an example : jsfiddle.net/UQTY2/38
Hmm...how odd. The fiddle doesn’t work for me on Chrome on Mac OS X. Whatever I change the URL to, it shows 'Something went wrong'.
jQuery only passes an event object to the error handler. See jQuery documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.