1

There is an external website which contains an html document for each day of the year, and I am trying to automatically load the document for the current date. However, the urls are not consistent across every document. Some of them end with .html while others end with .htm, and some of them might have a letter appended to the filename.

What I want to do is attempt to load a url, and if it results in a 404 error, try loading a different url.

For example, I might do window.location.replace(baseurl+'.htm'); and if that results in a 404 error, attempt window.location.replace(baseurl+'.html'); and if that results in a 404, try something else.

How can I determine when the server sends a 404 error and attempt to load a new url?

krampstudio
  • 3,519
  • 2
  • 43
  • 63
Zarxrax
  • 95
  • 1
  • 5
  • 1
    You can try with XHR before actually redirecting. Once you've redirected, your code will stop running and you're powerless to do anything about it. – Siguza Sep 16 '16 at 14:26

2 Answers2

2

Here's a function where you can pass in extensions to try, and it returns the first valid URL to a callback:

var request = new XMLHttpRequest();
var extensions = ['.html', '.htm'];
var count = 0;
var baseurl = 'http://blah.com/file';

function validUrl(baseurl, cb) {
  request.open('GET', baseurl + extensions[count], true);

  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
        cb(baseurl + extensions[count]);
      } else {
        count++;
        if (count === extensions.length) {
          cb(false);
        } else {
          validUrl(baseurl, cb);
        }
      }
    }
  };

  request.send();
}

// usage:

validUrl(baseurl, function(url) {
  if (url) {
    // use the valid url
  } else {
    console.log('no valid urls');
  }
});
SchattenJager
  • 333
  • 3
  • 15
  • Looks like this would work perfectly, but I get Cross-Origin Request Blocked from the server I am trying to read from, so I'll have to figure out something else I suppose. – Zarxrax Sep 16 '16 at 18:27
  • If they aren't on the same domain, you would have to use JSONP, have the server set the Access-Control-Allow-Origin header, or use [some other method](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy). – SchattenJager Sep 16 '16 at 18:41
1

As @Siguza said you can persist as an asynchronous request and validate it's status.

I suggest you to create a function which calls an AJAX and handle it's status returning to you if it's OK or not as a boolean. Something like:

// I'm  building an function to validate the URL
function checkValidURL(url) {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for older browsers
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Callback
  xmlhttp.onreadystatechange = function() {
    if (this.status == 200) {
      return true; // OK
    } else { // or -> } else if (this.status == 404) {
      return false; // Ops, something happen..
    }
  };
  // AJAX configuration
  xmlhttp.open("GET", url, false); // <- "false" for a synchronous request
  xmlhttp.send();
}

Simple example of use:

if (!checkValidURL("http://www.my_url")) {
    console.log("invalid URL"); 

    // Call or check other URL
} else {
    // It's OK, proceed with the business rules
}

Functions can wait AJAX requests by setting asynchronous "false", like: Is there any way to wait for AJAX response and halt execution?

Community
  • 1
  • 1
RPichioli
  • 3,245
  • 2
  • 25
  • 29
  • This isn't going to work because the function will return before the AJAX resolves. – SchattenJager Sep 16 '16 at 15:32
  • Updated, my fault synchronous was true. – RPichioli Sep 16 '16 at 16:32
  • Thanks, looks like the code is good, but I am getting Cross-Origin Request Blocked error, so I might need to rethink my approach here. – Zarxrax Sep 16 '16 at 18:05
  • Your function still returns before `xmlhttp.send()` does. – SchattenJager Sep 16 '16 at 18:51
  • You're welcome @Zarxrax, I suggest you to take a look into questions about CORS + xmlHttpRequest like: http://stackoverflow.com/questions/23272611/make-cors-ajax-requests-using-xmlhttprequest and http://stackoverflow.com/questions/13400594/understanding-xmlhttprequest-over-cors-responsetext .. hope it could help you – RPichioli Sep 16 '16 at 18:52