user526206 user526206 - 1 month ago 5
Javascript Question

How to check if URL is available or not using javascript

I am trying to use jQuery to check if URL is available or not. I am using the below Javascript code to verify this but it works for only HTTP URLs. If the URL is HTTPS it fails and I get the error

alert
.

var backendUrl = "https://myserver:8081/app/test.jsp";
$.ajax({
type: "GET",
url: backendUrl
}).done(function (result) {
console.log("working");
window.location.href = backendUrl;
}).fail(function () {
alert(Sorry URL is not access able");
});


Can someone tell me a reason and some more precise way to check if URL is available or not using javascript.

Answer

This is what I use to check if a URL exists:

function UrlExists(url, cb){
            jQuery.ajax({
                url:      url,
                dataType: 'text',
                type:     'GET',
                complete:  function(xhr){
                    if(typeof cb === 'function')
                       cb.apply(this, [xhr.status]);
                }
            });
        }

        UrlExists('-- Insert Url Here --', function(status) {
            if(status === 200) {
                -- Execute code if successful --
            } else if(status === 404) {
                -- Execute code if not successful --
            }else{
               -- Execute code if status doesn't match above --
            }
        });

There are many status codes so you can change out the 404 to whatever code you want to match or just put the code you want to execute in the last else case and that code will execute if the status does not match any of the requested status codes.