views:

94

answers:

5

Hi, I have a link

<a href="http://www.example.com"&gt;Hello&lt;/a&gt;

when i click the link it should check the page is exist or not.If exist goes to that page(www.example.com) or if the page is not exist redirect to another Page.

A: 

"check if a page exist with ajax" search gives http://www.webdeveloper.com/forum/archive/index.php/t-144464.html

Cedric
+1  A: 

why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.

tenfour
A: 

Another way to do this is is with PHP.

You could add

<?php
if (file_exists('/index.php')) 
{ 
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>

And then

<a href="<?php echo $url; ?>Link</a>
MadsK
What if PHP is not running on the OP's webservers? It would be perfectly valid to generate that page using, say, ASP.NET.
Billy ONeal
This was just ONE other way to do it.
MadsK
+2  A: 

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.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt; 
<script type="text/javascript">
<!--

$.fn.checkPageExists = function(defaultUrl){

    $.each(this, function(){

        var $link = $(this);

        $.ajax({
            url: $link.attr("href"),
            error: function(){
                $link.attr("href", defaultUrl);
            }
        });
    });
};

$(document).ready(function(){
    $("a").checkPageExists("default.html");
});
//-->
</script> 
Buh Buh
Making it an onClick event handler would reduce the burden of making all the requests all the time, so it would only check when the user clicks the link (instead of all links always) reducing wait time and traffic
Allbite
@Allbite You could, but then the user would have to click the link and wait for an ajax request to conclude. If this is slow then the link might just appear broken.
Buh Buh
A: 

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 reccommend 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',
    url: 'http://yoursite.com/page.html',
success: function() {
        // page exists
},
error: function() {
        // page does not exist
}
});

See also: http://api.jquery.com/jQuery.ajax/

Cthulhu