Reputation: 14950
I have a button which links to another page. Before I click that link, I want to check if that page currently returns an error or if it is not existing. How can I code this? Is this possible? I want to disable the link if it is not existing or if it returns an error.
Upvotes: 7
Views: 1403
Reputation: 7141
Ajax on clicking every request, even if it's as HEAD request (which is what you generally SHOULD use to test for a url's existence as that's why that HTTP verb exists in the first place), just strikes me as an incredibly bad idea, even if you could get over the likely insurmountable cross domain issues (unless you involve some sort of server-side check invoked by ajax). Now, I suppose you might be able to save responses at some place so that links aren't rechecked (on both client or server side), but this strikes me still as an incredibly over-complicated solution to a problem that generally doesn't need solving.
Upvotes: 1
Reputation: 5692
Note that I'd do this on server side. However as your tags are related to jquery, I post a solution you may try with jquery.
using jquery you can:
var link = $('#id_of_your_a_element');
$.ajax(
url: link.attr('href'),
error: function() {
link.hide();
}
);
EDIT
As ribot noted, this example does only hide the link. If you want to disable it you can prevent the default behavior when user clicks the link:
link.click(function(e) {
e.preventDefault();
});
or alternatively just remove the href attribute:
link.removeAttr('href');
Upvotes: 3
Reputation: 9931
As someone had asked, what is the server side programming language you're using, if any?
Check out the answers here: How to get status code of remote url using Javascript/Ajax but NOT using jQuery?. Same question as this, and the answers cover all the bases.
Upvotes: 2
Reputation: 183
You could use ajax to load the page and then parse it to see if there's an error before you then redirect the user. I would also include some kind of note to the user as to why the link isn't working.
Upvotes: 3