So, fiddling with AJAX, let’s do a little Hello Worlding:
And here’s a div:
<div id="ajaxtest"> <em>(although you can't see it as a separate div, this text will be replaced)</em></div>(although you can’t see it as a separate div, this text will be replaced)
Go on, watch the div text above, and click the button.
The request object is first set up at the script’s execution, but the only thing we do with it is tell it what to do when its “ready state” changes; that is, when the request shifts from not initialised, to set up, to having been sent, to being in process, to completion.
These states are numbered 0-4 respectively. Hold that thought; we’ll use it later. Suffice to say that, on the script’s execution, we now have an otherwise anonymous function that will be called when the ready state changes.
Now, in order for something interesting to happen, we click the button. That kicks off startRequest(), which in turn sets up a asynchronous request to ajaxtest.php, and submits it with no parameters (that’s the null). Asynchronous means we don’t sit around waiting for a response, and that’s why we need the readystatechange callback function.
So, when something interesting happens to the xhr object, the ready state changes (e.g. when we get a response back after sending our request). The browser then executes the anonymous function: first, the function checks that the request is complete – remember Ready State 4 above? don’t forget the ready state changes several times per request. We only want to read the response text once, at completion. Once the function has checked the request has been successfully completed, it then uses the xhr’s response-text to fill in the div called “ajaxtest”.
Et voila, we have “Hello World” in AJAX.Advertisements