Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to check http status codes

Tags:

javascript

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?

like image 492
Deepak Mittal Avatar asked Dec 20 '11 05:12

Deepak Mittal


People also ask

How do I check my HTTP status code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

What is http200?

The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.


1 Answers

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>
like image 178
Shalom Craimer Avatar answered Nov 03 '22 00:11

Shalom Craimer