5

I want to display profile pictures from gravatar for only those users who have a picture set. Doing this server side means doing around 100 HEAD requests to gravatar for checking 404 codes and appropriately outputting img tags for each request.

So, I want to implement a javascript function where I can just output 100 urls for which javascript can check the http status codes and output the appropriate image tags dynamically. Is that even possible? How?

2
  • However you happen to retrieve the image URL in Javascript will no doubt give you access to the request's status code. Commented Dec 20, 2011 at 5:36
  • That's the question. How do I retrieve the image URLs status codes? Cross Domain Ajax? Commented Dec 20, 2011 at 6:10

1 Answer 1

7

The keyword you're missing is "status code" (that's what we collectively call all the HTTP response codes of 200, 404, 500, etc). I'm going to assume you're using jQuery, in which case, all the documentation you need for doing AJAX is at http://api.jquery.com/jQuery.ajax/

Here's a simple example for a request that displays an alert, but only if a 404 status code is returned (lifted almost verbatim the link above):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
   $(function() {
      var url = "some_url";
      $.ajax(url,
      {
         statusCode: {
         404: function() {
            alert('page not found');
         }
      }
   });   
});
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

If the image is outside your domain you will see: No 'Access-Control-Allow-Origin' header is present on the requested resource.
@elGEoRgETheKiLLa Is there any way of overcoming that? I am planing to make a javascript snippet to open sequential images based on a base url with a number on it, and go both directions. If the base url is xxx10.jpg, I'd like to test both xxx09.jpg and xxx9.jpg to know the correct one and load the rest of them (01, 02, 03... or 1, 2, 3...) correctly.
Doesn't this code actually download the page at the given URL? Is there any way just to check the response status, without actually downloading the contents?
@Marc Yes, there is a way. HTTP allows sending "HEAD" instead of "GET", and that only returns the headers (including the status code). I'm not sure whether it's possible to generate that using Javascript AJAX libraries. I've never done it :)

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.