Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  158] [ 1]  / answers: 1 / hits: 23100  / 8 Years ago, wed, november 2, 2016, 12:00:00

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.


More From » jquery

 Answers
12

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.


[#60206] Monday, October 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
daquanmilesw questions
;