- Joined
- Mar 26, 2019
- Messages
- 64
- Reaction score
- 29
- First Language
- English
- Primarily Uses
- RMMV
Hello, party people in the place to be-
I have the following Frankenstein function:
Unfortunately, it seems to return false even if I use a valid and existing URL.
I have a feeling this has to do with the function not waiting for the XMLHttpRequest to complete. Save inserting a manual wait command, is there a better way to wait for the request to complete before returning a result?
Otherwise, what am I doing wrong?
As ever, thank you in advance!
I have the following Frankenstein function:
Code:
$._urlExists = function(url_to_check) {
var result = false;
// check if string is valid url format, source: https://stackoverflow.com/a/5717133
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
switch (!!pattern.test(url_to_check)) {
case true:
// check if url exists, source: https://stackoverflow.com/a/24297372
var reader = new XMLHttpRequest();
reader.open('get', url_to_check, true);
reader.onreadystatechange = (function() {
if (reader.readyState === 4) {
//check to see whether request for the file failed or succeeded
if ((reader.status == 200) || (reader.status == 0)) {
result = true;
};
};
});
reader.send(null);
break;
};
return result;
};
I have a feeling this has to do with the function not waiting for the XMLHttpRequest to complete. Save inserting a manual wait command, is there a better way to wait for the request to complete before returning a result?
Otherwise, what am I doing wrong?
As ever, thank you in advance!

