I am making a chatroom script and it appears that the problem seems to be that my setTimeout's are conflicting.
The logic is as follows:
- Run a login check every x seconds
- Run a trigger check every x seconds
The login check is a first priority, and may take some time to process.
The trigger check looks up the database, checks whether or not chatWindow = 1 (it is set to 1 when a message is posted) and if it equals 1, do some more Ajax to build the message list.
I have only tried this script in Firefox.
I am looking for a way to have both those setTimeout's running concurrently, and avoid conflicts. Is threading the answer?
My code is as follows (It's quite long):
The php/html
Expand|Select|Wrap|Line Numbers
- <?php
- $dbc = mysql_connect("localhost","xxx","")or die(mysql_error());
- mysql_select_db("xxx")or die(mysql_error());
- $a1 = $_REQUEST['a1'];
- if($a1) {
- switch($a1) {
- /* Chatters */
- case 'refreshChatters':
- $response = '';
- $e1 = "SELECT * FROM chatters";
- $e2 = mysql_query($e1,$dbc);
- while($e3 = mysql_fetch_array($e2)) {
- $response .= $e3['nickname'].'|';
- }
- echo 'doRefreshChatters(\''.$response.'\')';
- exit;
- break;
- /* Chat */
- case 'refreshChat':
- $response = '';
- $chatId = $_POST['chatId'];
- $e1 = "SELECT * FROM messages WHERE chatId = '$chatId'";
- $e2 = mysql_query($e1,$dbc)or die(mysql_error());
- while($e3 = mysql_fetch_array($e2)) {
- $response .= $e3['message'].'|';
- }
- echo 'doRefreshChat(\''.$response.'\')';
- exit;
- break;
- /* Authentication */
- case 'login':
- $fEmailAddress = $_REQUEST['fEmailAddress'];
- $fPassword = $_REQUEST['fPassword'];
- $e1 = "SELECT * FROM chatters WHERE emailAddress = '$fEmailAddress' AND password = '$fPassword'";
- $e2 = mysql_query($e1,$dbc);
- if(mysql_num_rows($e2) > "0") {
- $e3 = mysql_fetch_array($e2);
- $uid = $e3['id'];
- $rand = gettimeofday(true);
- $cid = substr(crypt($rand),0,200);
- $loginTime = date("Y-d-m H:i:s");
- $r1 = "UPDATE chatters SET loginTime = '$loginTime',
- cid = '$cid' WHERE id = '$uid'";
- $r2 = mysql_query($r1,$dbc)or die(mysql_error());
- setrawcookie("chatroom", $cid);
- $auth = crypt($cid,$loginTime);
- $r1 = "UPDATE triggers SET chatWindow = '1'";
- $r2 = mysql_query($r1,$dbc);
- header("Location: chatroom.php?auth=$auth");
- } else {
- echo '<p id="loginMsg">Incorrect login details.</p>';
- }
- break;
- case 'checkLogin':
- if(!$_COOKIE) {
- echo 'doCheckLogin(\'loggedIn=0\')';
- exit;
- } else {
- $cid = $HTTP_COOKIE_VARS["chatroom"];
- // If there is a cookie, then check the cid for one in the db
- $e1 = "SELECT loginTime FROM chatters WHERE cid = '$cid'";
- $e2 = mysql_query($e1,$dbc);
- // If there is no match, then logout
- if(mysql_num_rows($e2) == "0") {
- echo 'doCheckLogin(\'loggedIn=0\')';
- exit;
- } else {
- $e3 = mysql_fetch_array($e2);
- // If there is a match, then check the auth variable with the timestamp, cid combo
- $loginTime = $e3['loginTime'];
- $dbAuth = crypt($cid,$loginTime);
- $ajAuth = $_POST['auth'];
- if($dbAuth !== $ajAuth) {
- // If it does not equal the same, logout
- echo 'doCheckLogin(\'loggedIn=0\')';
- exit;
- } else {
- // Otherwise stay logged in
- echo 'doCheckLogin(\'loggedIn=1\')';
- exit;
- }
- }
- }
- exit;
- break;
- case 'logout':
- setcookie ("chatroom", "", time() - 3600);
- echo 'doLogout()';
- exit;
- break;
- case 'sendMessage':
- $message = $_POST['message'];
- $cid = $HTTP_COOKIE_VARS["chatroom"];
- // find user information
- $e1 = "SELECT id FROM chatters WHERE cid = '$cid'";
- $e2 = mysql_query($e1,$dbc);
- // If not found, log them out
- if(mysql_num_rows($e2) == "0") {
- echo 'doCheckLogin(\'loggedIn=0\')';
- exit;
- } else {
- $e3 = mysql_fetch_array($e2);
- $chatter = $e3['id'];
- $chatId = $_REQUEST['chatId'];
- $timestamp = date("Y-d-m H:i:s");
- $r1 = "INSERT INTO messages (chatId,chatter,message,timestamp)
- VALUES ('$chatId','$chatter','$message','$timestamp')";
- $r2 = mysql_query($r1,$dbc);
- // Set refresh trigger
- $t1 = "UPDATE triggers SET chatWindow = '1'";
- $t2 = mysql_query($t1,$dbc);
- // echo 'doTest(\''.$message.'\')';
- }
- exit;
- break;
- /* Triggers */
- case 'checkTriggers':
- $e1 = "SELECT chatWindow FROM triggers";
- $e2 = mysql_query($e1,$dbc);
- $e3 = mysql_fetch_array($e2);
- if($e3['chatWindow'] == "1") {
- $r1 = "UPDATE triggers SET chatWindow = '0'";
- $r2 = mysql_query($r1,$dbc);
- echo 'refreshChat()';
- exit;
- }
- exit;
- break;
- }
- }
- ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
- <title></title>
- <link rel="stylesheet" href="chatroom.css" />
- </head>
- <body>
- <?php
- if(!$_COOKIE["chatroom"]) {
- ?>
- <div id="login">
- <form method="post" action="chatroom.php?a1=login">
- <div class="form">
- <label for="fEmailAddress">Email address</label>
- <input type="text" name="fEmailAddress" id="fEmailAddress" />
- <br />
- <label for="fPassword">Password</label>
- <input type="text" name="fPassword" id="fPassword" />
- <br />
- <input type="submit" value="Login »" />
- </div>
- </form>
- </div>
- <?php } else { ?>
- <div id="chat">
- <div id="options"><a href="?a1=doLogout">Logout</a></div>
- <div id="chw"></div>
- <div id="cw"></div>
- <br />
- <div id="messageBox">
- <input type="text" size="40" name="message" id="message" /> <input type="button" onclick="sendMessage()" value="send" />
- </div>
- </div>
- <script type="text/javascript" src="chatroom.js"></script>
- <script type="text/javascript">
- var welcome = 'Welcome!';
- var auth = '<?php echo $_GET['auth']; ?>';
- startChat(welcome);
- </script>
- <?php } ?>
- </body>
- </html>
Expand|Select|Wrap|Line Numbers
- var t; // Timer
- var chatId = '1';
- var processing = ''; // For threading the requests?
- function startAjax(obj)
- {
- var obj;
- try{
- ajaxRequest=new XMLHttpRequest()}
- catch(e){
- try{
- ajaxRequest=new ActiveXObject("Msxml2.XMLHTTP")}
- catch(e){
- try{
- ajaxRequest=new ActiveXObject("Microsoft.XMLHTTP")}
- catch(e){
- alert("Your browser does not appear to support this application.");
- return false}
- }
- }
- return obj}
- function doAjax(action,auth,vars) {
- startAjax('ajaxRequest');
- ajaxRequest.onreadystatechange = function() {
- if (ajaxRequest.readyState == 4) {
- var a1 = ajaxRequest.responseText;
- eval(a1);
- }
- }
- var uid = Math.random();
- var str = 'a1='+action;
- str +="&uid="+uid;
- str +="&auth="+auth;
- if(vars) {
- var varsParts = vars.split("|");
- var i = 0;
- for(var i = 0; i < varsParts.length-1; i++) {
- var varsSingles = varsParts[i].split("#");
- str += "&"+varsSingles[0]+"="+varsSingles[1];
- }
- }
- var url = "chatroom.php";
- ajaxRequest.open("POST",url,true);
- ajaxRequest.setRequestHeader("Content-Type",
- "application/x-www-form-urlencoded; charset=UTF-8");
- ajaxRequest.send(str);
- }
- function makeElem(elem,id,text,dElem) {
- var dElem = document.getElementById(dElem);
- var e1 = document.createElement(elem);
- e1.setAttribute('id',id);
- var r1 = document.createTextNode(text);
- e1.appendChild(r1);
- dElem.appendChild(e1);
- }
- function doTest(response) {
- alert(response);
- }
- /* Triggers */
- function doCheckTriggers() {
- while(processing = '') {
- doAjax('checkTriggers',auth,false);
- }
- }
- var v1;
- function checkTriggers() {
- doCheckTriggers();
- v1 = setTimeout("checkTriggers()",2000);
- }
- /* Chatters */
- function refreshChatters() {
- doAjax('refreshChatters',auth,false);
- }
- function doRefreshChatters(chatters) {
- var chatters = chatters.split("|");
- for (var i = 0; i < chatters.length; i++) {
- makeElem('div','chatter',chatters[i],'chw');
- }
- }
- /* Chat */
- function refreshChat() {
- var vars = "chatId#"+chatId+"|";
- doAjax('refreshChat',auth,vars);
- }
- function doRefreshChat(messages) {
- document.getElementById('cw').nodeValue = '';
- var messages = messages.split("|");
- for (var i = 0; i < messages.length; i++) {
- makeElem('div','message-'+messages[i],messages[i],'cw');
- }
- }
- /* Authentication */
- function checkLogin() {
- processing = '1';
- doAjax('checkLogin',auth,false);
- }
- function logout() {
- doAjax('logout',auth,false);
- }
- function doLogout() {
- window.location = "chatroom.php?a1=login";
- clearTimeout(t);
- refresh();
- }
- function doCheckLogin(loggedIn) {
- switch(loggedIn) {
- case 'loggedIn=0':
- logout();
- break;
- }
- processing = '';
- }
- function doAuth() {
- checkLogin();
- t = setTimeout("doAuth()",5000);
- }
- /* Send message */
- function sendMessage() {
- while(processing = '') {
- var message = document.getElementById('message').value;
- var vars = "message#"+message+"|chatId#"+chatId+"|";
- doAjax('sendMessage',auth,vars);
- var message = document.getElementById('message').value = '';
- }
- }
- /* DOM setup */
- function setupChattersWindow() {
- makeElem('div','title','Chatters','chw'); // Make header
- }
- /* Start chatroom */
- function startChat() {
- doAuth();
- setupChattersWindow();
- refreshChatters();
- checkTriggers();
- }