user526206
user526206

Reputation:

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.

Upvotes: 4

Views: 24701

Answers (2)

Action Coding
Action Coding

Reputation: 830

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.

Upvotes: 9

user6852337
user6852337

Reputation:

Can't you just use a relative path?

e.g app/test.jsp - https://myserver:8081/app/test.jsp

            var backendUrl = "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");
             });

If you're running on a local environment it's unlikely that you would have an SSL installed.

Upvotes: 1

Related Questions