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.
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
});
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.