473,386 Members | 1,602 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Ajax multiple setTimeout's problem

12
Hi

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
  1. <?php
  2. $dbc = mysql_connect("localhost","xxx","")or die(mysql_error());
  3. mysql_select_db("xxx")or die(mysql_error());
  4.  
  5. $a1 = $_REQUEST['a1'];
  6.  
  7. if($a1) {
  8.     switch($a1) {
  9.         /* Chatters */
  10.         case 'refreshChatters':
  11.             $response = '';
  12.             $e1 = "SELECT * FROM chatters";
  13.             $e2 = mysql_query($e1,$dbc);
  14.             while($e3 = mysql_fetch_array($e2)) {
  15.                 $response .= $e3['nickname'].'|';
  16.             }
  17.             echo 'doRefreshChatters(\''.$response.'\')';
  18.             exit;
  19.         break;
  20.         /* Chat */
  21.         case 'refreshChat':
  22.             $response = '';
  23.             $chatId = $_POST['chatId'];
  24.             $e1 = "SELECT * FROM messages WHERE chatId = '$chatId'";
  25.             $e2 = mysql_query($e1,$dbc)or die(mysql_error());
  26.             while($e3 = mysql_fetch_array($e2)) {
  27.                 $response .= $e3['message'].'|';
  28.             }
  29.             echo 'doRefreshChat(\''.$response.'\')';
  30.             exit;
  31.         break;
  32.         /* Authentication */
  33.         case 'login':
  34.             $fEmailAddress = $_REQUEST['fEmailAddress'];
  35.             $fPassword = $_REQUEST['fPassword'];
  36.             $e1 = "SELECT * FROM chatters WHERE emailAddress = '$fEmailAddress' AND password = '$fPassword'";
  37.             $e2 = mysql_query($e1,$dbc);
  38.             if(mysql_num_rows($e2) > "0") {
  39.                 $e3 = mysql_fetch_array($e2);
  40.                 $uid = $e3['id'];
  41.                 $rand = gettimeofday(true);
  42.                 $cid = substr(crypt($rand),0,200);
  43.                 $loginTime = date("Y-d-m H:i:s");  
  44.                 $r1 = "UPDATE chatters SET loginTime = '$loginTime',
  45.                 cid = '$cid' WHERE id = '$uid'";
  46.                 $r2 = mysql_query($r1,$dbc)or die(mysql_error());
  47.                 setrawcookie("chatroom", $cid);
  48.                 $auth = crypt($cid,$loginTime);
  49.                 $r1 = "UPDATE triggers SET chatWindow = '1'";
  50.                 $r2 = mysql_query($r1,$dbc);
  51.                 header("Location: chatroom.php?auth=$auth");
  52.             } else {
  53.                 echo '<p id="loginMsg">Incorrect login details.</p>';
  54.             }
  55.         break;
  56.         case 'checkLogin':
  57.             if(!$_COOKIE) {
  58.                 echo 'doCheckLogin(\'loggedIn=0\')';
  59.                 exit;
  60.             } else {
  61.                 $cid = $HTTP_COOKIE_VARS["chatroom"];
  62.                 // If there is a cookie, then check the cid for one in the db
  63.                 $e1 = "SELECT loginTime FROM chatters WHERE cid = '$cid'";
  64.                 $e2 = mysql_query($e1,$dbc);
  65.                 // If there is no match, then logout
  66.                 if(mysql_num_rows($e2) == "0") {
  67.                     echo 'doCheckLogin(\'loggedIn=0\')';
  68.                     exit;
  69.                 } else {
  70.                     $e3 = mysql_fetch_array($e2);
  71.                     // If there is a match, then check the auth variable with the timestamp, cid combo
  72.                     $loginTime = $e3['loginTime'];
  73.                     $dbAuth = crypt($cid,$loginTime);
  74.                     $ajAuth = $_POST['auth'];
  75.                     if($dbAuth !== $ajAuth) {
  76.                     // If it does not equal the same, logout
  77.                         echo 'doCheckLogin(\'loggedIn=0\')';
  78.                         exit;
  79.                     } else {
  80.                     // Otherwise stay logged in
  81.                         echo 'doCheckLogin(\'loggedIn=1\')';    
  82.                         exit;
  83.                     }
  84.                 }
  85.             }
  86.         exit;
  87.         break;
  88.         case 'logout':
  89.             setcookie ("chatroom", "", time() - 3600);
  90.             echo 'doLogout()';
  91.             exit;
  92.         break;
  93.         case 'sendMessage':
  94.             $message = $_POST['message'];
  95.             $cid = $HTTP_COOKIE_VARS["chatroom"];
  96.             // find user information
  97.             $e1 = "SELECT id FROM chatters WHERE cid = '$cid'";
  98.             $e2 = mysql_query($e1,$dbc);
  99.             // If not found, log them out
  100.             if(mysql_num_rows($e2) == "0") {
  101.                 echo 'doCheckLogin(\'loggedIn=0\')';
  102.                 exit;
  103.             } else {
  104.             $e3 = mysql_fetch_array($e2);
  105.             $chatter = $e3['id'];
  106.             $chatId = $_REQUEST['chatId'];
  107.             $timestamp = date("Y-d-m H:i:s");
  108.             $r1 = "INSERT INTO messages (chatId,chatter,message,timestamp)
  109.             VALUES ('$chatId','$chatter','$message','$timestamp')";
  110.             $r2 = mysql_query($r1,$dbc);
  111.             // Set refresh trigger
  112.             $t1 = "UPDATE triggers SET chatWindow = '1'";
  113.             $t2 = mysql_query($t1,$dbc);
  114.             // echo 'doTest(\''.$message.'\')';
  115.             }
  116.         exit;        
  117.         break;
  118.         /* Triggers */
  119.         case 'checkTriggers':
  120.             $e1 = "SELECT chatWindow FROM triggers";
  121.             $e2 = mysql_query($e1,$dbc);
  122.             $e3 = mysql_fetch_array($e2);
  123.             if($e3['chatWindow'] == "1") {
  124.                 $r1 = "UPDATE triggers SET chatWindow = '0'";
  125.                 $r2 = mysql_query($r1,$dbc);
  126.                 echo 'refreshChat()';    
  127.                 exit;
  128.             }
  129.         exit;
  130.         break;
  131.     }
  132. }
  133. ?>
  134. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  135. <html xmlns="http://www.w3.org/1999/xhtml">
  136. <head>
  137. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  138. <title></title>
  139. <link rel="stylesheet" href="chatroom.css" />
  140. </head>
  141. <body>
  142.  
  143.     <?php
  144.  
  145.     if(!$_COOKIE["chatroom"]) {
  146.  
  147.     ?>
  148.  
  149.     <div id="login">
  150.         <form method="post" action="chatroom.php?a1=login">
  151.             <div class="form">
  152.                 <label for="fEmailAddress">Email address</label>
  153.                 <input type="text" name="fEmailAddress" id="fEmailAddress" />
  154.                 <br />
  155.                 <label for="fPassword">Password</label>
  156.                 <input type="text" name="fPassword" id="fPassword" />
  157.                 <br />
  158.                 <input type="submit" value="Login &raquo;" />
  159.             </div>
  160.         </form>
  161.     </div>
  162.  
  163.     <?php } else { ?>
  164.     <div id="chat">
  165.         <div id="options"><a href="?a1=doLogout">Logout</a></div>
  166.         <div id="chw"></div>
  167.         <div id="cw"></div>
  168.  
  169.         <br />
  170.         <div id="messageBox">
  171.             <input type="text" size="40" name="message" id="message" />&nbsp;<input type="button" onclick="sendMessage()" value="send" />
  172.         </div>
  173.     </div>
  174.     <script type="text/javascript" src="chatroom.js"></script>
  175.     <script type="text/javascript">
  176.     var welcome = 'Welcome!';
  177.     var auth = '<?php echo $_GET['auth']; ?>';
  178.     startChat(welcome);
  179.     </script>
  180.  
  181.     <?php } ?>
  182. </body>
  183. </html>
  184.  
The Ajax/js
Expand|Select|Wrap|Line Numbers
  1. var t; // Timer
  2. var chatId = '1';
  3. var processing = '';        // For threading the requests?
  4.  
  5. function startAjax(obj)
  6. {
  7.     var obj;
  8.     try{
  9.     ajaxRequest=new XMLHttpRequest()}
  10.     catch(e){
  11.         try{
  12.         ajaxRequest=new ActiveXObject("Msxml2.XMLHTTP")}
  13.         catch(e){
  14.             try{
  15.             ajaxRequest=new ActiveXObject("Microsoft.XMLHTTP")}
  16.             catch(e){
  17.                 alert("Your browser does not appear to support this application.");
  18.             return false}
  19.         }
  20.     }
  21. return obj}
  22.  
  23. function doAjax(action,auth,vars) {
  24.     startAjax('ajaxRequest');
  25.     ajaxRequest.onreadystatechange = function() {
  26.     if (ajaxRequest.readyState == 4) {
  27.             var a1 = ajaxRequest.responseText;
  28.             eval(a1);
  29.  
  30.         }
  31.     }
  32.     var uid = Math.random();
  33.     var str = 'a1='+action;
  34.     str +="&uid="+uid;
  35.     str +="&auth="+auth;
  36.     if(vars) {
  37.         var varsParts = vars.split("|");
  38.         var i = 0;
  39.         for(var i = 0; i < varsParts.length-1; i++) {
  40.             var varsSingles = varsParts[i].split("#");
  41.             str += "&"+varsSingles[0]+"="+varsSingles[1];
  42.         }
  43.     }
  44.     var url = "chatroom.php";
  45.     ajaxRequest.open("POST",url,true);
  46.     ajaxRequest.setRequestHeader("Content-Type",
  47.     "application/x-www-form-urlencoded; charset=UTF-8");
  48.     ajaxRequest.send(str);
  49. }
  50. function makeElem(elem,id,text,dElem) {
  51.     var dElem = document.getElementById(dElem);
  52.     var e1 = document.createElement(elem);
  53.     e1.setAttribute('id',id);
  54.     var r1 = document.createTextNode(text);
  55.     e1.appendChild(r1);
  56.     dElem.appendChild(e1);
  57. }
  58. function doTest(response) {
  59.     alert(response);    
  60. }
  61. /* Triggers */
  62. function doCheckTriggers() {
  63.     while(processing = '') {
  64.     doAjax('checkTriggers',auth,false);
  65.     }
  66. }
  67. var v1;
  68. function checkTriggers() {
  69.     doCheckTriggers();
  70.     v1 = setTimeout("checkTriggers()",2000);
  71. }
  72.  
  73. /* Chatters */
  74. function refreshChatters() {
  75.     doAjax('refreshChatters',auth,false);
  76. }
  77. function doRefreshChatters(chatters) {
  78.     var chatters = chatters.split("|");
  79.     for (var i = 0; i < chatters.length; i++) {
  80.         makeElem('div','chatter',chatters[i],'chw');    
  81.     }
  82. }
  83.  
  84.  
  85. /* Chat */
  86. function refreshChat() {
  87.     var vars = "chatId#"+chatId+"|";
  88.     doAjax('refreshChat',auth,vars);
  89. }
  90. function doRefreshChat(messages) {
  91.     document.getElementById('cw').nodeValue = '';    
  92.     var messages = messages.split("|");
  93.     for (var i = 0; i < messages.length; i++) {
  94.         makeElem('div','message-'+messages[i],messages[i],'cw');    
  95.     }
  96. }
  97.  
  98.  
  99.  
  100. /* Authentication */
  101. function checkLogin() {
  102.     processing = '1';
  103.     doAjax('checkLogin',auth,false);
  104. }
  105. function logout() {
  106.     doAjax('logout',auth,false);    
  107. }
  108. function doLogout() {
  109.     window.location = "chatroom.php?a1=login";
  110.     clearTimeout(t);
  111.     refresh();
  112. }
  113. function doCheckLogin(loggedIn) {
  114.         switch(loggedIn) {
  115.         case 'loggedIn=0':
  116.             logout();
  117.         break;
  118.     }
  119.     processing = '';
  120. }
  121. function doAuth() {
  122.     checkLogin();
  123.     t = setTimeout("doAuth()",5000);
  124. }
  125. /* Send message */
  126. function sendMessage() {
  127.     while(processing = '') {
  128.         var message = document.getElementById('message').value;
  129.         var vars = "message#"+message+"|chatId#"+chatId+"|";
  130.         doAjax('sendMessage',auth,vars);
  131.         var message = document.getElementById('message').value = '';
  132.     }
  133. }
  134.  
  135.  
  136. /* DOM setup */
  137. function setupChattersWindow() {
  138.     makeElem('div','title','Chatters','chw');                // Make header
  139. }
  140.  
  141.  
  142. /* Start chatroom */
  143. function startChat() {
  144.     doAuth();
  145.     setupChattersWindow();
  146.     refreshChatters();
  147.     checkTriggers();
  148. }
  149.  
Mar 12 '07 #1
1 2888
acoder
16,027 Expert Mod 8TB
The problem is that the same variable is being used for more than one request. You need to use separate ones for each request to avoid conflict, e.g. ajaxRequest, ajaxRequest2, etc.
Jun 4 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

17
by: petermichaux | last post by:
Hi, Is it possible for an AJAX request to be left open for multiple responses? This could avoid repetitive polling of the server. Thanks, Peter
17
by: Steve-O | last post by:
The following code works great in FireFox, Opera, Netscape, Safari, and Gecko, but NOT IE. Why? I tried using 'native' js with setInterval and setTimeout, but I get the same result. My IE...
3
by: markus.rietzler | last post by:
i want to do (multiple) file upload(s) and display a progress bar. with firefox and safari it is no problem at all. only IE makes some problems. my script is based on ajax-uploader, which can be...
6
by: Nico VanHaaster | last post by:
Hello all, I have run across an issue with IE 6.0+. I have a page that makes an XMLHttpRequest to the webserver to update a report on the page. The first time you hit the refresh report button...
3
by: work.Yehuda | last post by:
I'm Trying to write a chat width AJAX. For so far it works fine in Firefox browser, The only problem I had is width the Explorer. The function setTimeOut doesn't seem to work well width AJAX. The...
6
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick...
3
JamieHowarth0
by: JamieHowarth0 | last post by:
Hi folks, I have a bit of a headache. I've finally added all the nice finishing touches to my own website (static only with a bit of DHTML). Now I've just converted the whole thing to AJAX with a...
4
by: lak | last post by:
Hi friends, I have to parse a XML file and when it is changed I need to change in the front end. If I use the settimeout() then it is working. But I don't what to use the settimeout() function. ...
20
by: Bryan A | last post by:
Is there a way to add a timeout to this script so that it times out at a certain time. So it would be auto updating every 2seconds and it would timeout like after 100 seconds with a message?. ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.