AJAX Repetitive Request Step By Step Tutorial - Part 2: After understand how to use JavaScript function to create repetitive request, we will apply by creating simple application.
In this post, we build a application that request random number from server. It always request random number with internal 1000 milliseconds.
First, create server script. Create a file named "random.php" within www/test/ajax. Enter following code:
<?
$result = rand(0,100);
header('Content-type: text/xml');
$dom = new DOMDocument();
$datas = $dom->createElement('datas');
$dom->appendChild($datas);
$random = $dom->createElement('random');
$randomText = $dom->createTextNode($result);
$random->appendChild($randomText);
$datas->appendChild($random);
$xmlString = $dom->saveXML();
echo $xmlString;
?>
Then, create client side. Create a file named "repetitive.html" within www/test/ajax. Enter following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Repetitive Request</title>
<script type="text/javascript">
var requestCounter = 0;
var interval = 1;
var serverAddress = "random.php";
var xmlHttp = createXmlHttpRequestObject();
// creates XMLHttpRequest Instance
function createXmlHttpRequestObject(){
// will store XMLHttpRequest object
// at here
var xmlHttp;
// works all exceprt IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE 6 or older
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){ }
}
// return object or display error
if (!xmlHttp)
alert("Error creating the XMLHttpRequest Object");
else
return xmlHttp;
}
function process()
{
myDiv = document.getElementById("myDivElement");
myDiv.innerHTML = "";
if(xmlHttp)
{
try
{
xmlHttp.open("Get",serverAddress, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e)
{
alert("Can't connect to server\n" + e.toString());
}
}
}
function handleRequestStateChange()
{
myDiv = document.getElementById("myDivElement");
if(xmlHttp.readyState == 1)
{
myDiv.innerHTML += "Request status: 1 (loading) <br/>";
}
else if (xmlHttp.readyState == 2)
{
myDiv.innerHTML += "Request status: 2 (loaded) <br/>";
}
else if (xmlHttp.readyState == 3)
{
myDiv.innerHTML += "Request status: 3 (interactive) <br/>";
}
else if (xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
try
{
handleXMLData();
}
catch(e)
{
alert("Error reading the response: " + e.toString());
}
}
else
{
alert("Problem retrieving data:\n" + xmlHttp.statusText);
}
}
}
function handleXMLData()
{
var xmlResponse = xmlHttp.responseXML;
// error handling for IE and Opera
if (!xmlResponse || !xmlResponse.documentElement){
throw("1. Invalid XML Structure:\n " + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
//error handling for Firefox
if (rootNodeName == "parseerror"){
throw("2. Invalid XML Structure:\n " + xmlHttp.responseText);
}
var xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "datas" || !xmlRoot.firstChild){
throw("3. Invalid XML Structure:\n " + xmlHttp.responseText);
}
var xmlData = xmlRoot.firstChild;
var dataNodeName = xmlData.nodeName;
if (dataNodeName != "random"){
throw("4. Invalid XML Structure:\n " + xmlHttp.responseText);
}
requestCounter++;
myDiv = document.getElementById("myDivElement");
myDiv.innerHTML += "Request status: 4 (complete). <br />Request # " + requestCounter + ": ";
myDiv.innerHTML += xmlHttp.responseText;
setTimeout("process();", interval = 1000);
}
</script>
</head>
<body onload="process()">
Our collections:
<div id="myDivElement" />
</body>
</html>
Point your browser to http://localhost/test/ajax/repetitive.html. You may get like this: