Catching 404 Page Not Found Error for All Empty Links on Page

Hello all,

On my home page, there are a lot of empty/missing pages as I’m beginning to add more content. I want to come up with a scripting bit that can check when a broken link has been clicked. Instead of the page directing to a custom 404 error page and going back to the last page visited, I thought that JavaScript could be used to detect a broken link through the .ajax() method and display an alert on the page for a moment that says the page does not exist yet. I made an attempt at what the .ajax() structure would look like, but I need some help coming up with a solution. Should I just stick with a custom 404 error page?

$(document).ready(function() {
    $("a").click(function() {
        $.ajax({
            type: "GET",
            url: "window.location.href",
            datatype: "xml",
            error: function(jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 404) {
                    //display the page not existing alert div on home page
                }
            },
            success: //don't do anything. just visit the page
    )};
});

});

Thanks for your suggestion on how this might be accomplished.

-ty

In general, it won’t be a good idea to bind all the anchors to make ajax call; just to find the 404 status code. Better to go with custom 404 page.

On the other hand, i can think of one possible scenarios for implementing the same. May you find it useful -

  • First, if those broken links are known then we can add css class like “broken-link” to those anchors. With this class selector, we can write a function in javascript to show alert/popup/informationBox on the page.

     $('.broken-links').on('click', function(){
         // show alert or information box
     });
    

Similar thread - http://stackoverflow.com/questions/1591401/javascript-jquery-check-broken-links

~ Lokesh

Excellent point and simple solution, Lokesh. Thank you!
I look forward to implementing a new class to empty links in the page.

edit: The problem still is how to stop the links from navigating to the empty 404 page with JavaScript inside the JS target you posted earlier. I didn’t see anything else but .ajax() discussed on the linked thread.

if you want to stop the native behavior of link, there are two ways to achieve the same.

  • Pass “event” as function argument and use preventDefault() API

     $('.broken-links').on('click', function(event){
         // prevent default behavior of link
         event.preventDefault();
     });
    
  • Second, set href attribute value as “javascript:void(0)”.

     <a href="javascript:void(0)" class="broken-link">anchor text</a>
    

Let me know, if this helps to solve your issue.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.