Page 1 of 1

date display 'sticks'

Posted: Wed Nov 23, 2011 11:25 am
by inosent1
I use the following ajax code to call another php page, which has the effect of 'refreshing' w/o refreshing. the idea is to be a seamless refresh, etc


Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/JavaScript">
var xmlHttp;
 
function getDiscussion(str)
{
    var url="test.php";
    xmlHttp=GetXmlHttpObject(stateChanged)
    xmlHttp.open("GET", url , true)
    xmlHttp.send(null)
}
 
function stateChanged()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
        document.getElementById("myAJAXdiv").innerHTML=xmlHttp.responseText;
    }
}
 
function GetXmlHttpObject(handler)
{
    var objXmlHttp=null
 
    if (navigator.userAgent.indexOf("Opera")>=0)
    {
        alert("Opera not supported...")
        return;
    }
    if (navigator.userAgent.indexOf("MSIE")>=0)
    {
        var strName="Msxml2.XMLHTTP"
        if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
        {
            strName="Microsoft.XMLHTTP"
        }
        try
        {
            objXmlHttp=new ActiveXObject(strName)
            objXmlHttp.onreadystatechange=handler
            return objXmlHttp
        }
        catch(e)
        {
            alert("Error. Scripting for ActiveX might be disabled")
            return
        }
    }
    if (navigator.userAgent.indexOf("Mozilla")>=0)
    {
        objXmlHttp=new XMLHttpRequest()
        objXmlHttp.onload=handler
        objXmlHttp.onerror=handler
        return objXmlHttp
    }
} 

function startWatching()
{
 getDiscussion(this.value);
 setTimeout("startWatching()",2000);
}
</script>
</head>

<body onLoad="startWatching();">
	<div style="margin: 10px;" id="myAJAXdiv"></div>
</body>
</html>




the code of 'test.php' includes this

Code: Select all

$timea = date("is", time()); 
echo $timea;


As you can see in the ajax code, the time interval for the 'refresh' is shown as 2000, or 2 seconds. when you load the code you will see, *generally* that the time changes every 2 seconds.

however, sometimes it will 'freeze up' and hang for about 5-8 seconds before showing the next time value. for my purposes this is inconvenient. i need a reliable clock that seamlessly re-displays every two seconds, w/o 'sticking'

Re: date display 'sticks'

Posted: Wed Nov 23, 2011 11:39 am
by twinedev
You will probably get a better answer posting this in the correct section instead of PHP Code.

Re: date display 'sticks'

Posted: Wed Nov 23, 2011 11:53 am
by maxx99
Yep its Javascript.... anyway.... why do you need AJAX requests to get time!?
http://www.w3schools.com/js/js_obj_date.asp

If you don't want rely on client time, you can can sync with server at start and every 5 mins or so (with e.g. ajax request).