For asynchronous requests, a callback function should be
created to check if the response is ready to be processed.
Create a callback function that will check if the response is ready to be
processed.
AJAX - Using a Callback Function
For asynchronous requests, a callback function should be
created to check if the response is ready to be processed.
AJAX - Creating a Callback Function
Create a callback function that will check if the response is ready to be
processed.
Simply update the code from the previous chapter (the code still works in all browsers):
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
// set the callback function
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// set the callback function
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
} |
The callback function is registered via the onreadystatechange property of
the XMLHttpRequest object.
Three important properties of the XMLHttpRequest object when using a callback
function:
| Property |
Description |
| onreadystatechange |
Stores a function (or the name of a function) to be called automatically
each time the readyState property changes |
| readyState |
Holds the status of the server's response. Changes value from 0 to 4
during a request cycle:
0: not initialized
1: connection established
2: request received
3: processing
4: finished and response is ready |
| status |
200: "OK"
404: Page not found |
The callback function looks like this:
function stateChange()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
// process whatever has been sent back here
document.getElementById('test').innerHTML=xmlhttp.responseText;
}
else
{
alert("There was a problem in the returned data");
}
}
} |
Complete Example
var xmlhttp;
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
function stateChange()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
// process whatever has been sent back here
document.getElementById('test').innerHTML=xmlhttp.responseText;
}
else
{
alert("There was a problem in the returned data");
}
}
}
Let AJAX change this text
Click Me
Click Me
Note: Do not forget to declare the xmlhttp variable outside the
functions. Both functions use it!
|