<a href="http://www.example.com">Hello</a>
when I click the link it should check whether the page exists or not. If it exists it goes to that page (www.example.com) but if the page doesn't exist it redirects to another URL.
<a href="http://www.example.com">Hello</a>
when I click the link it should check whether the page exists or not. If it exists it goes to that page (www.example.com) but if the page doesn't exist it redirects to another URL.
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:See also: http://api.jquery.com/jQuery.ajax/
If you are happy to use jQuery you could do something like this. When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like:
select * from htmlstring where url="http://google.com"
. You can use the "REST query" they have on that page as a starting point for your code.Here's some code that would accept a full URL and use YQL to detect if that page exists:
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
Based on the documentation for XMLHttpRequest:
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
Another way to do this is is with PHP.
You could add
And then