Disable HTML link if link url returns error

I have a button that links to another page. Before clicking this link, I want to check if this page is currently returning an error or if it does not exist. How can I encode this? Is it possible? I want to disable the link if it does not exist or if it returns an error.

+6
source share
4 answers

You can use ajax to load the page and then analyze it to see if there is an error before redirecting the user. I would also like to tell the user some note about why the link is not working.

+3
source

Please note that I will do this on the server side. However, since your tags are jquery related, I am posting a solution that you can try using jquery.

using jquery you can:

var link = $('#id_of_your_a_element'); $.ajax( url: link.attr('href'), error: function() { link.hide(); } ); 

EDIT

As noted in this example, this example hides the link. If you want to disable it, you can prevent the default behavior when the user clicks on the link:

 link.click(function(e) { e.preventDefault(); }); 

or just remove the href attribute:

 link.removeAttr('href'); 
+3
source

How did someone ask which server-side programming language you use, if any?

Check out the answers here: How to get the remote URL status code using Javascript / Ajax but NOT using jQuery? . The same question as this one and the answers cover all the bases.

+2
source

Ajax, when clicking on each request, even if it is a HEAD request (which you MUST usually use to check for the existence of a URL, such as why this HTTP verb exists in the first place), it just amazes me like an incredibly bad idea , even if you can overcome the potential insurmountable cross-domain issues (unless you use some kind of server-side validation caused by ajax). Now, I suppose, you could save the answers in some place so that the links are not double-checked (both on the client side and on the server side), but it still amazes me as an incredibly complex solution to the problem, which, as a rule, Do not need a solution.

+1
source

Source: https://habr.com/ru/post/923155/


All Articles