For a chess-script i needed to update a site remotely when it's the user's turn. As PHP is only server sided I needed a workaround.
I didn't want to simply refresh the page / a frame, because the browser would regularly spit out an annoying "CLICK"-sound.
This is the way i tried to solve the problem:
The site that needs to be updated sometime (the chess board - or chat-room or sth. like that) contains the following code:
site.php:
<?
$lk = mysql_connect("localhost","user","pass");
mysql_select_db("databasename");
$sql = "SELECT id FROM tablename ORDER BY id DESC LIMIT 0,1"; // "id" is the unique primary key
$res = mysql_query($sql);
$last = mysql_result($res,0,"id");
?>
<head>
<script language="JavaScript">
<!--
function checkForUpdate()
{
checkframe.document.write("<script src='check.php?last=<? echo $last; ?>'></script>");
}
//-->
</script>
</head>
<body>
--- content from db here---
<p><iframe name="checkframe" width="0" height="0"></iframe></p>
<script language="JavaScript">window.setInterval("checkForUpdate()",10000);</script>
</body>
Every 10 seconds the script "check.php" is called (by the javascript written to checkframe). This PHP Script checks the Database if there are new entries by compairing $_GET['last'] and the actual last "id" in the database.
check.php:
<?
header("Content-type: application/x-javascript");
$lk = mysql_connect("localhost","user","pass");
mysql_select_db("databasename");
$sql = "SELECT id FROM tablename ORDER BY id DESC LIMIT 0,1";
$res = mysql_query($sql,$lk);
$actual = mysql_result($res,0,"id");
if ($_GET['last'] && ( $actual != $_GET['last'] ))
echo "parent.location.href='site.php?".time()."';"; // added time() to prevent loading from cache
?>
If there is a new entry, the site is remotely updated by JavaScript. It works fine.
But I don't know if the following problem can arise: The document in the checkframe is updated constantly -> Can that cause a timeout in the browser or other problems, that can crash the browser... ??
What do you think?
How do you solve this common problem?