Daniyal Javani
Daniyal Javani

Reputation: 235

Order of Run command in JavaScript

Obviously to talk to a server you would have to first send a request to the server, then recieve the response. However it appears in this code that you first recieve the response then in the next line send the request -- what is going on here?

    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","gethint.php?q="+str,true);
    xmlhttp.send();

Upvotes: 0

Views: 62

Answers (2)

apsillers
apsillers

Reputation: 116020

onreadystatechange is just a listener that runs when the request resolves.

Imagine your friend is helping you collect mail at the post office. You tell him:

"Whenever a worker gives you the package, check the name on the package is correct, then open it, assemble the contents, and bring it back to me at my house. Now, go to the post office!"

You've told your friend what to do when he gets your mail, and then you sent him out to go collect it.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71939

It doesn't receive the response first, it just sets up what to do when the response is received (which is never immediately, as this is an asynchronous operation). The order here actually doesn't matter.

Upvotes: 5

Related Questions