Click to See Complete Forum and Search --> : reload


sandy1028
09-29-2008, 02:53 AM
Hi,

The file I have named as time.php and id is 'time'.

Names is the function which is queried from the database Mysql.
When the database record changes I have to change the $time_val in time.php without hitting the refresh key.

The page has to dynamically change when the value gets changed in the database.


Please help me how can I do it using ajax


<?
$name = Names(1);
array_shift($name);
$time_val = $name[0];
?>

<html>

<head>
<script type="text/javascript">function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest!='undefined'){
try{
xmlhttp = new XMLHttpRequest();
} catch (e){
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();

function changeDiv(){
var url = "time.php";
http.open("GET", url, true);
http.send(null);
document.getElementById('time').innerHTML = http.responseText;</script>
</head>
<?php
echo '<body onLoad="window.setInterval("changeDiv()",1);">

<div id="time">'.$time_val.'</div>
</body>
</html>';
?>

bretticus
09-29-2008, 04:44 AM
Because the XMLHttpRequest call is asynchronous, you need to tell your javascript which function to fire when listening for a response. Thus, your function to change the div contents should be a sepearet function (not changeDIV() ). You can specify that function with the onreadystatechange property like so...

<script type="text/javascript">

// get your xmlhttp object...
var http = getHTTPObject();

function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest!='undefined'){
try{
xmlhttp = new XMLHttpRequest();
} catch (e){
xmlhttp = false;
}
}
return xmlhttp;
}

function changeDiv(){
if (http.readyState==4)
{
document.getElementById('time').innerHTML = http.responseText;
}
}

function getTime(){
var url = "time.php";
http.onreadystatechange=changeDiv;
http.open("GET", url, true);
http.send(null);
}
</script>

Make sure you call getTime() (or wahtevere you decide to call it) in your setInterval() function.