PDA

View Full Version : Update Only When Needed : PHP,Mysql ?


birdbrain24
03-31-2008, 01:21 AM
I was wondering if there was anyway that i could only tell the ajax to update when the mysql changes. Heres my script, i was using setTimeout but it really is a cpu hog being played over and over!

<?php ...

if($xmlhttp == 'true'){

$update = $_POST['update'];

if($update == 'true'){

echo '<strong>Username:</strong> ' . $users['username'] . ' <strong>Rank:</strong> ' . $users['rank'] . ' <strong>Cash:</strong> $' . number_format($users['cash']) . ' <strong>Vehicle:</strong> ' . $selected . ' <strong>Location:</strong> ' . $users['location'] . ' <strong>Reputation:</strong> ' . $users['reputation'];

}

} else {
?>
<!DOCTYPE ...

<head>
<script language="javascript" type="text/javascript">
function UpdateUserbar(){
var xmlhttp;

try{
xmlhttp = new XMLHttpRequest();
} catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert("Your browser do not support our technology!");
return false;
}
}
}

xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
document.getElementById('userbar').innerHTML = xmlhttp.responseText;
setTimeout('UpdateUserbar();', 1);
}
}
var params = "xmlhttp=" + "true" + "&" + "update=" + "true";
var url = "userbar.php";
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(params);
}
</script>
</head>
<body onload="UpdateUserbar();">
<div id="userbar"><!-- Userbar Here! --></div>
</body>
</html>
<?php
}
?>

tomws
03-31-2008, 06:07 PM
...i was using setTimeout but it really is a cpu hog being played over and over!

...
function UpdateUserbar(){
...
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
document.getElementById('userbar').innerHTML = xmlhttp.responseText;
setTimeout('UpdateUserbar();', 1);
}
}
}
...


I don't have a solution for your question (because I don't understand what you're asking), but I think this might be your CPU usage problem. Unless I misunderstand what's happening here, it looks like you're infinitely recursing the UpdateUserbar function. And yes: infinite recursion is a resource hog.

A1ien51
03-31-2008, 07:09 PM
Since there is no way to push data down from the client, you will need to look into COMET. Same basic ideayou are doing, except you make the request stay open on the server.

Plus there is no need to look for new data every millisecond. You should build it so that when the response comes back, you send up a new one. With the way you designed it, you are going to run out of bandwidth on your host in no time.

Eric