Skip to content

banner ajax
The Complete Reference: Ajax

Examples: Ready State

Note: There is an intentional delay between readystate 1 & 2. This shows the time from when the request is sent to when the data starts to return.

<!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=iso-8859-1" />
<title>Chapter 3 : XMLHttpRequest - Ready State</title>
<link rel="stylesheet" href="global.css" type="text/css" media="screen" />
<script type="text/javascript">
 
 
function createXHR()
{
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
 
   return null;
}
 
function sendRequest()
{
    var url = "https://ajaxref.com/ch3/helloworldslow.php";
    var readyStateOutput = document.getElementById("readyStateOutput");
    readyStateOutput.style.display = "";
    
    var xhr = createXHR();
 
    if (xhr)
     {
       readyStateOutput.innerHTML ="Before Open: readyState: " + xhr.readyState + "<br/>";
       xhr.open("GET",url,true);
       readyStateOutput.innerHTML += "After Open/Before Send: readyState: " + xhr.readyState + "<br/>";
       xhr.onreadystatechange = function(){handleResponse(xhr);};
       xhr.send(null);
     }
}
 
function handleResponse(xhr)
{
    var readyStateOutput = document.getElementById("readyStateOutput");
    readyStateOutput.innerHTML += "In onreadystatechange function: readyState: " + xhr.readyState + "<br/>";
}
 
window.onload = function () 
{ 
 document.requestForm.requestButton.onclick = function () { sendRequest(); };
};
</script>
 
</head>
<body>
 
<form action="#" name="requestForm">
  <input type="button" name="requestButton" value="Make Request" />
</form>
<div id="readyStateOutput" class="results" style="display:none;">&nbsp;</div>
 
</body>
</html>