Naveen P.N

Just another Blog to play with programming

Display Time continiously

leave a comment »

Time-Continous.html

  This sample code gets the time from server and display continiously using AJAX.

<html>
  <head>
    <title>AJAX with PHP: Quickstart</title>
    <script type="text/javascript">
// stores the reference to the XMLHttpRequest object
var xmlHttp=null;
if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }

// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{

	if(xmlHttp)
	{
// proceed only if the xmlHttp object isn't busy
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{

    		xmlHttp.open("GET", "time.asp", true);
		xmlHttp.onreadystatechange = handleServerResponse;

  	}
  	else
        setTimeout('process()', 1000);
	}
	xmlHttp.send(null);
}

// executed automatically when a message is received from the server
function handleServerResponse()
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4)
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200)
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseText;

      document.getElementById("divMessage").innerHTML =
                                            '<i>' + xmlResponse + '</i>';
      // restart sequence
      setTimeout('process()', 1000);
    }
    // a HTTP status different than 200 signals an error
    else
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

</script>
  </head>
  <body onload='process()'>
    Server Time:
    <div id="divMessage" />
  </body>
</html> 

Time.asp

<%
response.expires=-1
response.write(time)
%>

Written by Naveen P.N

March 24, 2009 at 5:29 am

Posted in AJAX

Leave a Reply