xtempore
xtempore

Reputation: 5505

jQuery: Get detail of image loading error

I have a javascript that calls a server-side script (PHP) that serves up requested images. There are parameters passed in for the user and image key.

If the requested image does not exist I respond with a 404 error. If the image exists but the user does not have rights to access it, I respond with a 403 error.

Here's a simplified code example...

$img.error(function () {
        alert("Image not known or access denied.");
    })
    .attr("src", "getimg.php?key=horse&user=fred");

I'd like to give a different message depending on whether the problem is with the image key, or whether it is that the user does not have access.

Is there some way that I can either access the HTTP error code returned, or the text returned within the response?

Upvotes: 2

Views: 129

Answers (1)

Stephan Muller
Stephan Muller

Reputation: 27620

When you put the url to the PHP script directly in the src attribute your javascript is not going to be aware of any errors in fetching the image. One way to solve this is to fire an AJAX request for the image:

$.ajax( "getimg.php?key=horse&user=fred" )
 .fail(function(jqXHR) {
    // do something here when the image wasn't loaded
    if(jqXHR.status === 403) {
       // access denied
    } else if(jqXHR.status === 404) {
      // not found
    }
  });

The jqXHR object contains information like what status code was thrown, what the response from the server was, etc. More information here.

Note that I only use the .fail() callback here and don't do anything when the image load was successful. It makes little sense to AJAX in an image, you can still just set the src to the right url and that will take care of everything when the image could be loaded. The only reason we're using AJAX here is in case something goes wrong.

Upvotes: 1

Related Questions