-4

Is there anyway to check if the location of a html <a> tag exists before leaving the page and display a message to the user rather than redirecting to a 404 page. I'm also using jQuery if that helps.

Something like this:

  • When tag clicked run a method call a function
  • Check if href of link
  • Exists if link exists redirect
  • Else display error message to user
Mardzis
  • 760
  • 1
  • 8
  • 21
Conor Groco
  • 17
  • 1
  • 4

1 Answers1

1

It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work - browser security prevents cross-domain calls (the same origin policy).

If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does - the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499).

Example:

$.ajax({
type: 'HEAD',  //HEAD request will only return the headers,with response codes 200 - 299
url: 'http://yoursite.com/page.html',
success: function() {
    // page exists
},
error: function() {
    // page does not exist
}
});
halfer
  • 19,824
  • 17
  • 99
  • 186
Priyank
  • 3,778
  • 3
  • 29
  • 48