-1

I'm trying to work with a XMLHttpRequest and got the basic code working, but can't get the function with the code below to return a boolean variable to say if it's worked or not:

var xhr = new XMLHttpRequest();
var success = false;

xhr.open('HEAD', sourceurl, true);
xhr.send();
xhr.onreadystatechange=function(){
    if (xhr.readyState === 4){   //if complete
        if(xhr.status === 200){  //check if "OK" (200)
            //success
            console.log('success');
            return true;

        } else {
            // fail
            console.log('fail' );
            return false;

        }
    } 
};

The console logs show the right thing but when wrapping this code in a function it simply won't give any indication on whether it worked or not.

Any help would be appreciated!

EDIT: Not a duplicate as cannot use jQuery in my example and existing solutions there do not work.

  • You could set a variable in your enclosing function (say `success`) ... and then set it to true or false where you do the `return true` or `false`... and then return this value from the outer function ...because the return value does not cascade to the outer function ... – Exception_al May 03 '17 at 09:18
  • Thanks, I've tried setting the variable of success (the variable's in script already) but it still won't equal true even if console.log returns true. – stevenkellow May 03 '17 at 09:24
  • Checked the post mentioned by @kaiido - I can't use jQuery for my solution and the second solution for not using jQuery fails too – stevenkellow May 03 '17 at 09:32

1 Answers1

0

The onreadystatechange function is asynchronous, so it isn't returning to anything. You want to look at using callback functions if you want to wrap it in an outer function, which basically means calling a function that will handle the result of the HTTP request.

Liam MacDonald
  • 301
  • 1
  • 9