0

I have a function isOnline(), which looks like this:

function isOnline() {
    var request=new XMLHttpRequest(); 

    request.onreadystatechange=function() {
        if(request.readyState==4) {
            if(request.responseText=="online")
                return true;    
        }    
    }
    request.open("GET","onlinecheck.php?user=user",false);
    request.send();

    return false;
}

If I run document.write(isOnline()); for testing , I ALWAYS get false, (undefined if i dont write return false; , I get undefined.

How do I 'wait' before the readyState is 4 and return true after that ?

AKS
  • 18,983
  • 3
  • 43
  • 54
harveyslash
  • 5,906
  • 12
  • 58
  • 111

1 Answers1

2

You need to focus on few things:


In case you decide to do it synchronously:

function isOnline() {
    var request=new XMLHttpRequest(); 

    request.open("GET","www.google.com/",false);
    request.send();

    /* check the readyState, you can also check for status code */
    if (request.readyState === 4)
        // put other conditions here if you need to    
        return true;
    else
        return false;
}

// It returns true
Community
  • 1
  • 1
AKS
  • 18,983
  • 3
  • 43
  • 54