0

I have question about chechking file exists.

I have this piece of code.

function fileExists(url) {
  if (url) {
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    req.send();
    console.log("exists");
    return true;
  } else {
    console.log("no exists");
    return false;
  }
}

But it says me that file is exists. But it doesn't exists. In fact on my URL is 404 error XML file. Is possible somehow detect if requested URL is JSON? I need to return true only if checked file is JSON.

Thank you

Roman Šimr
  • 47
  • 12
  • 1
    Possible duplicate of [detect 404 error on page load](https://stackoverflow.com/questions/26630650/detect-404-error-on-page-load#answer-26631181) – Chris S. Aug 16 '18 at 15:29

1 Answers1

4

Since this is a synchronous request, you can just try to parse the responseText you get back and if it fails to parse, you know it's not JSON:

        var res = req.responseText;
        try {
             res = JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }

If it were not a synchronous request, this would work:

If you look at the XMLHttpRequest docs, you'll see that in order to receive data back from an XMLHttpRequest, you need to add a callback function:

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        // Request finished. Do processing here.
    }
}

If you wanted to check if your request is JSON, you could do this:

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        var res = this.responseText;
        try {
             JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }
    }
}
Zach Bloomquist
  • 5,309
  • 29
  • 44
  • 1
    you should probably explain that a status 200 code means a successful request...this whole code block could use some explanation for future users... – DrCord Aug 16 '18 at 15:41
  • 2
    @KirkLarkin - I did post my own answer and despite it being correct I got trolled and downvoted and no one would tell me why so I deleted it – DrCord Aug 16 '18 at 15:50