-1

How to return to the calling function (the function above). I would like to return true if the file exists when doing UrlExists('file.png') :

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, true);
    http.onerror = function(e){
                            //console.log('......onerror: ' + JSON.stringify(e));
                            if (typeof e !== 'undefined'){
                                return false
                            }   
                        };
    http.send();
    return http.onerror();
}
Louis
  • 2,144
  • 9
  • 51
  • 104
  • You need to do a synchronous call so that it stops and waits. You don't need to know if it's the `UrlExists()` function (which I don't believe you can get). That means it needs to be `http.open('HEAD', url, false)`. – Jared Farrish Oct 25 '14 at 13:15
  • I am really looking to use the asynchronous call, can you help with it? – Louis Oct 25 '14 at 13:20
  • The third argument for `http.open()` is `async: true`, so pass false and it will be synchronous. I have that at the end of my last comment. `;)` – Jared Farrish Oct 25 '14 at 13:21
  • sorry I meant asynchronous – Louis Oct 25 '14 at 13:24
  • You can't do it with an asynchronous call. You have to follow the common pattern for asynchronous operations and have your "UrlExists" function accept a callback argument. – Pointy Oct 25 '14 at 13:24
  • Sorry, what you want to do with returning `http.onerror` you can't do when it's asynchronous. You have to refactor your methods to account for this (welcome to asynchronous development). – Jared Farrish Oct 25 '14 at 13:25
  • Can you write UrlExists with the callback the way it should be done ? – Louis Oct 25 '14 at 13:29
  • Ok I did this in my answer and offered some tips for validating the file because if you send multiple async requests there is no guarantee they will come back in the order you made them. – nothingisnecessary Oct 25 '14 at 13:47
  • The linked "answer" is for jQuery `.ajax()`, but this question has no jQuery tag and is only using native javascript – nothingisnecessary Oct 25 '14 at 13:54

1 Answers1

0

Use XMLHttpResponse as async. Because async responses may not be received in the order that they are requested and since you may be checking for multiple files it may be a good idea to check the responseURL property before acting on the case where the file does not "exist" (is not found or returns error, etc.)

jsFiddle example: http://jsfiddle.net/5f42L6nz/4/

Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

function UrlExists(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true); // true => async request
    xhr.onload = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // URL found, do stuff for "exists"
                alert("url exists:\r\n" + xhr.responseURL);
            } else {
                // URL not found, could check xhr.status === 404, etc.
                // do stuff when URL not found, but no exception/error thrown
                alert("not found or unexpected response:\r\n" + xhr.responseURL);
            }
        }
    };
    xhr.onerror = function (e) {
        console.error(xhr.statusText);
    };
    xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");
nothingisnecessary
  • 5,964
  • 29
  • 54
  • thanks for your answer. Is it possible to modify the code so that `UrlExists` returns true or false, instead of poping an alert ? – Louis Oct 25 '14 at 17:23
  • No, not with the asynchronous approach. You would need to create a callback function that did something with the result instead. So instead of calling `alert()`, create and call a new function like this: `function UrlExists_Callback(isValid) { if (isValid === true) { // do stuff if file exists } else { // do stuff if not } }` – nothingisnecessary Oct 25 '14 at 17:25
  • ok I see, thanks a lot ! – Louis Oct 25 '14 at 17:26