1

I have a Admin panel(I am creating) with a list of URLs. I would like create script which can check to see if the urls is currently working or goes to a 404 page. Is this possible?

David Allen
  • 1,123
  • 2
  • 10
  • 24
  • 1
    possible dup of http://stackoverflow.com/questions/3922989/how-to-check-if-page-exists-using-javascript ? – Fabrizio Calderan Mar 05 '12 at 13:32
  • see [here](http://stackoverflow.com/questions/4282151/how-can-i-ping-a-server-from-javascript) – Alberto De Caro Mar 05 '12 at 13:34
  • @FabrizioCalderan the link you gave has BAD solution which is not relevant to the question here( 404 only). – Royi Namir Mar 05 '12 at 13:35
  • @RoyiNamir look at the most-rated response (by fwielstra)... it has code and a good explanation – Fabrizio Calderan Mar 05 '12 at 13:36
  • @FabrizioCalderan thats the one im talking about. he doesnt check any reponse code . where the OP specified 404. – Royi Namir Mar 05 '12 at 13:38
  • imho, the opposite of "working link" is not necessarily a "404 error". A "server busy", "not authorized" or other errors can still occur. So there's no real need to reinvent the wheel when other users had already answered to the same kind of question. – Fabrizio Calderan Mar 05 '12 at 13:43

3 Answers3

4

You can do this:

<a href="/somelink" id="test1">Link1</a> <span id="result1"></span>
$.ajax($("#test1").attr("href"), {
  statusCode: {
    404: function() {
      $("#result1").html("not working");
    },
    200: function() {
      $("#result1").html("working");
    }
  }
});
Lee
  • 296
  • 2
  • 16
3

Ajax calls to Get/Head will work only if the URL to check belongs to same site. If you are trying to check for the URL which belongs to some other site, then you will get Cross-site reference error.

In that case , you need check this at server side. Create an ajax call to server side method. At server side , create HttpRequest for the url and check its HttpResponse and reply back to ajax call.

S.Akruwala
  • 1,446
  • 12
  • 8
3

try this : (assuming the page are in the same domain)

  $.ajax(
  {
      type: "get",
      url: 'page.aspx',
      cache: false,
      statusCode: {
                    404: function ()
                       {
                          alert('page not found');
                       }
                   },
      async: true
  });
Royi Namir
  • 144,742
  • 138
  • 468
  • 792