N3Cr0M0rPh N3Cr0M0rPh - 4 years ago 116
Javascript Question

Error when attempting to check if page exists or not (function returns undefined)

I am attempting to check if a URL exists or not. The function is supposed to return true if the url is not 404, and false if it is 404'd.

Now for some reason this function is returning "undefined"

Here is my code:

function checkURL(url){
var xmlhttp; // initialize the request object
// All the browsers except for the old IE
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //old IE
}
if (xmlhttp) {
xmlhttp.open("HEAD", url, true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status!=404) {
return true;
} else {
return false;
}
}
xmlhttp.send(null);
}
}


Thanks in advance. Cheers.

Answer Source

The return value of checkURL will be undefined until the AJAX request finishes. I would approach this with a callback like this:

function checkURL(url, cb) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        cb(true)
      } else {
        cb(false)
      }
    };

    request.onerror = function() {
      cb(false)
    };

    request.send();
}


checkURL('https://www.reddit.com/r/javascript.json', function(status) {
    if (status) {
        // did not 404
    } else {
        // 404 or error
    }
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download