0

I am trying to call a REST API with JavaScript and XMLHttpRequest. The URL is: "http://quotes.stormconsultancy.co.uk/random.json"

This works from the browser window, but when I try to run it as javascript in the browser, it always returns a status of 0 (Even when I substitute the URL with any another URL for a simple GET request - for e.g. http://www.yahoo.com, I still get the same result.

Here is the code:

(function callRestAPI() {
  var request = new XMLHttpRequest();
  var url = "http://quotes.stormconsultancy.co.uk/random.json";

  request.onreadystatechange = function () {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        alert("The response was: " + request.responseText);
      } else if (request.status === 0) {
        alert("The response was a status code of 0");
      }
    }
  };
  request.open("GET", url, "false");
  request.send();

})();

I am at a loss on how to figure this out. Any help would be appreciated.

Thanks,

  • Jay

(Note: I get the same result with Firefox 47 and Chrome 51

jaytsecan
  • 1
  • 1

2 Answers2

0

Isn't this a Cross-Origin Request issue? Since you're calling the URL in ajax from another domain it gets blocked, thats why when you're doing it from the browser window it works (same domain) but from where you're hosting your script it doesn't?

Mokkun
  • 708
  • 4
  • 14
0

Cross-Origin Request, the Server has to provide some whitelist to let you do what you want, read here: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

enter image description here

webdeb
  • 12,993
  • 5
  • 28
  • 44