I'm trying to write a "fileExists" function in Javascript which simply sends a request to the server and returns false if a 404 status is sent back.
The function works perfectly, but I can't seem to suppress the error message I get in the Google Chrome console stating: GET /something/foobar 404 (Not Found)
.
Does anyone know a way to work around this?
For reference, here's the code I'm using:
var fileExists = function(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
return req.status === 200;
};
Thanks in advance!
I don't think there's a way to prevent the console from stating that loading a ressource failed. There's nothing wrong with that actually.
You might however better use a HEAD request instead of really loading the ressource with GET. Try
function fileExists(url) {
var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send();
return req.status !== 404;
}
If you really want to avoid 404 statuses, install a service on your server that you can query whether a file/path is available. It would always return the XML/JSON/textual response with a 200 OK status, regardless of that contains true
or false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With