473,322 Members | 1,510 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,322 software developers and data experts.

How do i use setTimeout for a chat system

hello guys
now i am working on a chat system and i am having a problem with the setTimeout can anyone help me this is all i have done

javascript

Expand|Select|Wrap|Line Numbers
  1. $(document).ready(function()
  2. {
  3.     updateMsg();
  4. });
  5.  
  6. function updateMsg()
  7. {
  8.     $.ajax({
  9.         url:"db.php",
  10.         type:"GET",
  11.         success:function(data){
  12.             addMessages();
  13.         }
  14.     });
  15.     setTimeout("updateMsg()",7000);
  16. }
  17.  
  18. function addMessages()
  19. {
  20.     $.ajax({
  21.         url:"db.php",
  22.         type:"GET",
  23.          data:"name="+$("#name").val()+"&to="+$("#user2").val()+"&cc="+$("#user").val()+"&msg="+$("#msg").val(),  
  24.         success:function(data)
  25.         {
  26.         $("#t1").prepend(data);}
  27.     });
  28. }
  29.  
php
Expand|Select|Wrap|Line Numbers
  1. foreach($_POST as $key => $value)
  2. {
  3.     $key = mysql_real_escape_string($value, $dbconn);
  4. }
  5.  
  6.  
  7.  
  8. $user_select = mysql_query("SELECT * FROM User WHERE User_name = '$name'") 
  9.                             or die(mysql_error());
  10. $fetch_select = mysql_fetch_array($user_select);
  11. $user_check = mysql_num_rows($user_select);
  12.  
  13. if ($user_check == 0)
  14. {
  15.     mysql_query("INSERT INTO User (User_name) VALUES ('$name')") or die(mysql_error());
  16.  
  17.     $new_user = mysql_query("SELECT * FROM User WHERE User_ID = LAST_INSERT_ID()");
  18.  
  19.     $fetch_new_user = mysql_fetch_array($new_user);
  20.  
  21.     mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
  22.                  VALUES ('$fetch_new_user[User_ID]','$msg',NOW())") or die(mysql_error());
  23. }
  24.  
  25. else 
  26. {
  27.     mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
  28.                  VALUES ('$fetch_select[User_ID]','$msg',NOW())") or die(mysql_error());
  29. }
  30.  
  31. $sql = mysql_query("SELECT Msg_body,Date_Time,User_name
  32.                     FROM Messages,User
  33.                     WHERE From_user = User_ID
  34.                     AND Msg_ID = LAST_INSERT_ID()
  35.                     ORDER BY Date_Time DESC") or die(mysql_error());
  36.  
  37.     while($result = mysql_fetch_array($sql))
  38. {
  39. $mydata = '<tbody id="tbody1">
  40.      <tr class="highlight">
  41.     <td  width="30" id="bullet" align="center">
  42.     <a href="#" class="nohighlight">•</a></td>
  43.     <td width="30px" align="center" id="replyImg"><input type="image" src="css/images/reply_arrow.png" onClick="reply()"></input></td>
  44.     <td width="70" align="Left" id="time">'.$result["Date_Time"].'</td>
  45.     <td width="200" align="Left" id="from">'.$result["User_name"].'</td>
  46.     <td width="200" align="Left" id="to">'.$result[""].'</td>
  47.     <td id="showMsg">'.$result["Msg_body"].'</td>
  48. <td width="200" align="left" id="group">'.$result["Grp_abr"].'</td>        
  49. </tr>
  50. </tbody>';
  51.  
  52.     }
  53.  
  54.         echo $mydata;
  55.  
Jul 29 '09 #1
31 4158
gits
5,390 Expert Mod 4TB
i guess that you wanted to use setInterval() for continous execution ... or just call the timeout from the success-handler ...

kind regards
Jul 29 '09 #2
How? can you show me i have been working for 2 months on this and i am getting mad
Jul 29 '09 #3
gits
5,390 Expert Mod 4TB
:) just use:

Expand|Select|Wrap|Line Numbers
  1. window.setInterval(updateMsg, 7000);
  2.  
or:

Expand|Select|Wrap|Line Numbers
  1. function updateMsg() {
  2.     $.ajax({
  3.         url: 'db.php',
  4.         type: 'GET',
  5.         success: function(data) {
  6.             addMessages();
  7.             window.setTimeout(updateMsg, 7000);
  8.         }
  9.     });
  10. }
Jul 29 '09 #4
Hey i am so sorry but it didn't do the trick anyother ideas
i usually test it with 2 browser windows
Jul 29 '09 #5
gits
5,390 Expert Mod 4TB
post the code that you currently use ...
Jul 31 '09 #6
Hi
This is javascript
Expand|Select|Wrap|Line Numbers
  1. $(document).ready(function()
  2. {
  3.     updateMsg();
  4. });
  5.  
  6. function updateMsg()
  7. {
  8. $.ajax({
  9.         url:"db.php",
  10.         type:"POST",
  11.         success:function(data){
  12.     alert("Hello");
  13.         }
  14. });
  15. setTimeout("updateMsg()",7000);
  16. }
  17.  
  18. function addMessages()
  19. {
  20. $.ajax({
  21.         url:"db.php",
  22.         type:"POST",
  23.     data:"name="+$("#name").val()+"&to="+$("#user2").val()+"& cc="+$("#user").val()+"&msg="+$("#msg").val(),  
  24.     success:function(data)
  25.         {
  26.         $("#t1").prepend(data);}
  27. });
  28. }
and this is php
Expand|Select|Wrap|Line Numbers
  1. $name = $_POST['name'];
  2. $user2 = $_POST['to'];
  3. $user = $_POST['cc'];
  4. $msg = $_POST['msg'];
  5.  
  6. $user_select = mysql_query("SELECT * FROM User WHERE User_name = '$name'") 
  7.                             or die(mysql_error());
  8. $fetch_select = mysql_fetch_array($user_select);
  9. $user_check = mysql_num_rows($user_select);
  10.  
  11. if(isset($_POST['msg']) && $_POST['msg'] != '')
  12. {
  13.  if ($user_check == 0)
  14. {
  15.     mysql_query("INSERT INTO User (User_name) VALUES ('$name')") or die(mysql_error());
  16.  
  17.     $new_user = mysql_query("SELECT * FROM User WHERE User_ID = LAST_INSERT_ID()");
  18.  
  19.     $fetch_new_user = mysql_fetch_array($new_user);
  20.  
  21.     mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
  22.                  VALUES ('$fetch_new_user[User_ID]','$msg',NOW())") or die(mysql_error());
  23. }
  24.  
  25. else 
  26. {
  27.     mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
  28.                  VALUES ('$fetch_select[User_ID]','$msg',NOW())") or die(mysql_error());
  29.  }
  30. }
  31.  
  32. $sql = mysql_query("SELECT Msg_body,Date_Time,User_name
  33.                     FROM Messages,User
  34.                     WHERE From_user = User_ID
  35.                     AND Msg_ID = LAST_INSERT_ID()
  36.                     ORDER BY Date_Time DESC") or die(mysql_error());
  37.  
  38.     while($result = mysql_fetch_array($sql))
  39. {
  40. $mydata = '<tbody id="tbody1">
  41.      <tr class="highlight">
  42.     <td  width="30" id="bullet" align="center">
  43.     <a href="#" class="nohighlight">•</a></td>
  44.     <td width="30px" align="center" id="replyImg"><input type="image" src="css/images/reply_arrow.png" onClick="reply()"></input></td>
  45.     <td width="70" align="Left" id="time">'.$result["Date_Time"].'</td>
  46.     <td width="200" align="Left" id="from">'.$result["User_name"].'</td>
  47.     <td width="200" align="Left" id="to">'.$result[""].'</td>
  48.     <td id="showMsg">'.$result["Msg_body"].'</td>
  49. <td width="200" align="left" id="group">'.$result["Grp_abr"].'</td>        
  50. </tr>
  51. </tbody>';
  52.  
  53.     }
  54.  
  55.         echo $mydata;
Jul 31 '09 #7
dlite922
1,584 Expert 1GB
Use Firefox, then go to Tools -> Error Console to see your Javascript errors.



Dan
Jul 31 '09 #8
No errors at the error console
Even though i have firebug
Aug 1 '09 #9
gits
5,390 Expert Mod 4TB
you posted the same code as the first time .... with no adaptions i suggested? so try:

Expand|Select|Wrap|Line Numbers
  1. function updateMsg() {
  2.     $.ajax({
  3.         url: 'db.php',
  4.         type: 'POST',
  5.         success: function(data) {
  6.             alert('Hello');
  7.             window.setTimeout(updateMsg, 7000);
  8.         }
  9.     });
  10. }
is the alert working? if so the same function should be called 7 seconds later on and the alert should occur again and so on ...
Aug 1 '09 #10
Hey Gits
Ya the function works but it doesn't retrieve anything from the database
may be i have a problem with my php code i don't know
Aug 2 '09 #11
gits
5,390 Expert Mod 4TB
the updateMsg() function just does an XMLHttpRequest to db.php ... without sending any data ... is that your intention?
Aug 2 '09 #12
No i want to retrieve the last data added to the database
Aug 2 '09 #13
gits
5,390 Expert Mod 4TB
i guess the latest messages for the specific user? then you would need to send the users name, id or whatever with the call ... as i said ... currently you post nothing to php with the current call from updateMsg() ...
Aug 2 '09 #14
Hi Gits
I totally changed the code what do you think now it is still not working
javascript
Expand|Select|Wrap|Line Numbers
  1.     $(document).ready(function(){
  2.             timestamp = 0;
  3.             updateMsg();
  4.             $("form#chatform").submit(function(){
  5.                 $.post("db.php",{
  6.                             message: $("#msg").val(),
  7.                             name: $("#name").val(),
  8.                             action: "postmsg",
  9.                             time: timestamp
  10.                         }, function(data) {
  11.                     $("#msg").empty();
  12.                     addMessages(data);
  13.                 });
  14.                 return false;
  15.             });
  16.         });
  17.         function addMessages(data) {
  18.             alert(data);
  19.             //if($("status",data).text() == "2") return;
  20.             timestamp = $("time",data).text();
  21.             $("message",data).each(function(id) {
  22.                 message = $("message",data).get(id);
  23.                 $("#t1").prepend("<tr><td></td><td></td><td>"+$("name",message).text()+"</td><td></td><td>"+$("text",message).text()+"</td><td></td>");
  24.             });
  25.         }
  26.         /*<b>"+$("name",message).text()+
  27.                                     "</b>: "+$("text",message).text()+
  28.                                     "<br />*/
  29.         function updateMsg() {
  30.             $.post("db.php",{ time: timestamp }, function(data) {
  31.                 addMessages(data);
  32.             });
  33.             setTimeout('updateMsg()', 4000);
  34.         }
  35.  
php
Expand|Select|Wrap|Line Numbers
  1. foreach($_POST as $key => $value)
  2. {
  3.     $$key = mysql_real_escape_string($value, $dbconn);
  4. }
  5.  
  6. if(@$action == "postmsg")
  7. {
  8.     mysql_query("INSERT INTO Messages (`Msg_body`,`Date_Time`)
  9.                 VALUES ('$message',".time().")");
  10. }
  11.  
  12. $messages = mysql_query("SELECT Msg_body
  13.                          FROM Messages
  14.                          ORDER BY id ASC");
  15. if(mysql_num_rows($messages) == 0) $status_code = 2;
  16. else $status_code = 1;
  17.  
  18. echo "<?xml version=\"1.0\"?>\n";
  19. echo "<response>\n";
  20. echo "\t<status>$status_code</status>\n";
  21. echo "\t<time>".time()."</time>\n";
  22. if($status_code == 1)
  23. {
  24.     while($message = mysql_fetch_array($messages))
  25.     {
  26.         $message['Msg_body'] = htmlspecialchars(stripslashes($message['Msg_body']));
  27.         echo "\t<message>\n";
  28.         echo "\t\t<name>$message[From_user]</name>\n";
  29.         echo "\t\t<text>$message[Msg_body]</text>\n";
  30.         echo "\t</message>\n";
  31.     }
  32. }
  33. echo "</response>";
Aug 3 '09 #15
gits
5,390 Expert Mod 4TB
what JavaScript lib do you use? jQuery? ... what errors do occur?
Aug 3 '09 #16
jquery
No errors occur at all just not working
Aug 3 '09 #17
gits
5,390 Expert Mod 4TB
... if it's not working then somwhere has to be an error. so lets start to trace that down together. you start with:

Expand|Select|Wrap|Line Numbers
  1. $(document).ready(function() {
  2.     timestamp = 0;
  3.  
  4.     updateMsg();
  5.  
  6.     $("form#chatform").submit(function() {
  7.         $.post("db.php", {
  8.             message: $("#msg").val(),
  9.             name: $("#name").val(),
  10.             action: "postmsg",
  11.             time: timestamp
  12.         }, function(data) {
  13.             $("#msg").empty();
  14.             addMessages(data);
  15.         });
  16.         return false;
  17.     });
  18. });
  19.  
the first request is done by updateMsg() and the second is instantly done after this by submitting some form-data. so in both success-handlers you might trace the response ... what do you get back there?
Aug 3 '09 #18
Hey gits
I changed again to return an xml response now i want to know where to place the setTimeout
Expand|Select|Wrap|Line Numbers
  1.     function addMessages()
  2.     {
  3.             //alert($("#msg").val());
  4.         $.ajax({
  5.             url:"db.php",
  6.             type:"post",
  7.             data:"message="+$("#msg").val(),
  8.             datatype:"xml",
  9.             success:function(data)
  10.             {    $("#t1").prepend('<tr><td>bullet</td><td>reply</td><td>'+$("time",data).text()+'</td><td>De</td><td>A</td><td>'+$("message",data).text()+'</td><td>Gr</td></tr>');
  11.             }
  12.           });
  13.     }
  14.  
  15. function updateMsg()
  16. {
  17.     $.ajax({
  18.         url:"db.php",
  19.         type:"post",
  20.         datatype:"xml",
  21.         success:function(data)
  22.         {
  23.             addMessages();
  24.         }
  25.     });
  26. }    
Thanks
Aug 5 '09 #19
gits
5,390 Expert Mod 4TB
inside a success-handler and just call the method that should be called again.
Aug 5 '09 #20
Hi Gits
HELP ME
I am going crazy
take a look at the code and tell me what do you think
Can you test it please because if it doesnt work i will kill myself
Expand|Select|Wrap|Line Numbers
  1. $(document).ready(function()
  2. {
  3.     updateMessages();
  4.  
  5. })
  6.     function addMessages()
  7.     {
  8.             $.ajax({
  9.                 url:"db.php",
  10.                 type:"post",
  11.                 data:"message="+$("#msg").val()+"&action="+"post",
  12.                 success:function()
  13.                 {    
  14.                      updateMessages();
  15.                 }
  16.  
  17.               });
  18.         }
  19.     function updateMessages()
  20.     {
  21.             $.ajax({
  22.                 url:"db.php",
  23.                 type:"post",
  24.                 data:"action="+"update",
  25.                 datatype:"xml",
  26.                 success:function(data)
  27.                 {        $("#t1").prepend('<tr><td>bullet</td><td>reply</td><td>'+$("time",data).text()+'</td><td>De</td><td>A</td><td>'+$("message",data).text()+'</td><td>Gr</td></tr>');
  28.  
  29.                 }
  30.  
  31.               });
  32.     setTimeout("updateMessages",7000);            
  33.         }
Aug 7 '09 #21
gits
5,390 Expert Mod 4TB
wait a moment. let's first check what you have. is the code from post #19 working without a timeout ... so i mean ... do you get the result on the page the first time when it runs?
Aug 8 '09 #22
It runs onone page not the other
I want when i send the message it appears on both pages
Aug 9 '09 #23
gits
5,390 Expert Mod 4TB
ok i'm simply confused now. lets have a look at your latest code (i guess you use the code from post #21), since that is the latest thing that is to follow at the moment. when the doc is ready you call updateMessages() which itself should call updateMessages() after 7secs again but you have a syntax error here:

Expand|Select|Wrap|Line Numbers
  1. setTimeout("updateMessages", 7000);
must be:

Expand|Select|Wrap|Line Numbers
  1. setTimeout(updateMessages, 7000);
the better way would be to place it in the success-handler but the current calls should work then. your function addMessages() is useless now since it is never called?

and what do you mean with 2 pages? this is the first time you mention that it isn't just one?
Aug 9 '09 #24
Hey Gits
I want to achieve chatting between 2 clients so this is why i am using setTimeout
I want when i write a message on one page it appears on the 2 pages
If you have other questions this is my email [edit]removed[edit]
bacause i want to solve this problem
Aug 9 '09 #25
gits
5,390 Expert Mod 4TB
please don't post email-addresses in the technical forums, or do you want to get spammed? :) ... and at least it is against the posting rules.

to the problem: i think i don't get it quite well, let me summarize:

- you have written a webclient for a webchat-application
- you open it and log in as User A
- you are able to post msg and see the messages at this page?

-> that is the code that i saw until now ...

- now you open another page and open the client again
- you login with another user B

- here is the problem? what is not working? i don't understand what the timeout should have to do with that ... since both of the windows should use the same code?
Aug 10 '09 #26
Hi Gits
sorry i must have forgotten the rules
yes this is what i do

yes when i login with another user there is lag in time between messages
Aug 10 '09 #27
gits
5,390 Expert Mod 4TB
so the problem is the lag in time? ...
Aug 10 '09 #28
Hey Gits the problem is that the message don't appear on same pages at the same time
I want it to appear as if both clients are chatting when i send from one page last messages appear on both pages
This is the problem
Aug 10 '09 #29
gits
5,390 Expert Mod 4TB
this will not work ... you will always have to poll the messages from the client ... and in case you don't want to poll every second then you will have that delay ... that is the design of web-technology ...
Aug 12 '09 #30
So what should i do any ideas
Aug 12 '09 #31
gits
5,390 Expert Mod 4TB
you have to live with that issue ... what is the problem? max time between the appearing of the message after send is 7seconds ... to reduce it you might poll every second ... ? isn't that enough? with a webpage-based chat-client you don't have stateful connections and you cannot push the messages ...
Aug 12 '09 #32

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

Similar topics

3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
3
by: A | last post by:
Hi all! I am currently working on a project where I need to create a web-based chat application that will be used for auctions. If possible, could I get some advice on how to create chat...
5
by: John Bokma | last post by:
Hi, I am working on a simple chat program and want to use AJAX. In order to get the new lines added to the chat I need to call a server-side script, say every x seconds. A second way to get...
2
by: jason.m.ho | last post by:
Hello! I am trying to build an ajax chat system. Currently I have it so that when you chat, you upload your message to the database, and each client is polling that database to see if he/she has...
15
by: nikki_herring | last post by:
I am using setTimeout( ) to continuously call a function that randomly rotates/displays 2 images on a page. The part I need help with is the second image should rotate 3 seconds after the first...
0
The1corrupted
by: The1corrupted | last post by:
Alright, I've set up a chat system that only works half way... I need suggestions on how to make it work better... I'm trying to figure out a way to make $_SESSION viewable to all players by...
1
by: quill | last post by:
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...
1
oll3i
by: oll3i | last post by:
how do i run this example ? with openjms package com.ociweb.jms; import java.io.*; import javax.jms.*; import javax.naming.*;
1
oll3i
by: oll3i | last post by:
when i run it from bat (@start "CHAT to topic" run Chat)without durable subscriber the window for chat opens but when i added the durable subscriber to the code it stopped opening? import...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.