Under the Microscope: HTTP Ready States
So when exactly does the ready state of a request change? Here's a close-up look at the ready state of a request, and how it changes as a request is processed by a web server.
request.onreadystatechange = updatePage;This property tells the browser what function to run when the request's ready state changes. 1 Connection initializedAt this stage, the request knows how to connect, and what to connect to. request.send(null) ;With the connection initialized, the request is sent to the server. Web ServerThe server gets the request to the right script or program, and that program responds to the request. 2 Response in progressAt this stage, the browser makes the status and response headers from the server available. PHP Script 3 Getting server responseData is downloading into the request object, but the data's not ready to be used by your code yet. 4 Server response readyThe server's finished with your request, and any response data is available in the request object's responseText property.
As long as you remember the name of the property you use to set the callback function, you'll remember that the callback is run more than one time. Do you remember what the property was called?
It's onreadystatechange. So when the ready state changes from 1 to 2, for example, your callback function, updatePage(), gets run. In other words, updatePage() will run several times: when the ready state changes from 1 to 2, when it changes again from 2 to 3, and one more time, when the ready state changes from 3 to 4.
But the server only guarantees that it's got data you can use when the ready state is 4. So you need to check the current ready state before trying to update the order form, or the page might end up with bad or missing data.