0

I am trying to check HTTP status for a document. But getting trouble during function run. I have function

    function sitePresent(url) {
    var status = 1000;
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            status = 200;
        } else {
            status = 500;
        }
    };
    req.open("GET", url, true);
    req.send();
    return status;
}
alert(sitePresent(url));

But I get 500 (it is just test code). When I add alert popup into both of the conditions instead status = XXX I get two popups.

I think all in that block is executed. I am missing something.

Please how can I make a function that returns true or false depending on HTTP status?

Levi
  • 77
  • 7
  • 1
    That's because you're returning `status` before you receive a response from the server. The xmlhttprequest is asynchronous in nature. You might want to read up on how to use promises, as well as the modern `fetch()` method of making asynchronous requests. – Terry Feb 14 '20 at 09:09
  • 1
    check this - https://stackoverflow.com/a/8571617/1659563 – Sachin Feb 14 '20 at 09:09
  • Separately, looking at the name of your function, if you expect it to work for arbitrary URLs, it won't. See the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) for why. – T.J. Crowder Feb 14 '20 at 09:12
  • replace the this with req means req.readyState == 4 && req.status == 200 – Ali Torki Feb 14 '20 at 09:15
  • Thanks all, Sachin, your link helped really much, I will read more about topic. Thanks – Levi Feb 14 '20 at 09:41

0 Answers0