How do i use setTimeout for a chat system

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sarah aziz
    New Member
    • Sep 2007
    • 31

    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

    Code:
    $(document).ready(function()
    {
    	updateMsg();
    });
    
    function updateMsg()
    {
    	$.ajax({
    		url:"db.php",
    		type:"GET",
    		success:function(data){
    			addMessages();
    		}
    	});
    	setTimeout("updateMsg()",7000);
    }
    
    function addMessages()
    {
    	$.ajax({
    		url:"db.php",
    		type:"GET",
     		data:"name="+$("#name").val()+"&to="+$("#user2").val()+"&cc="+$("#user").val()+"&msg="+$("#msg").val(),  
            success:function(data)
    		{
    		$("#t1").prepend(data);}
    	});
    }
    php
    Code:
    foreach($_POST as $key => $value)
    {
    	$key = mysql_real_escape_string($value, $dbconn);
    }
    
    
    
    $user_select = mysql_query("SELECT * FROM User WHERE User_name = '$name'") 
    							or die(mysql_error());
    $fetch_select = mysql_fetch_array($user_select);
    $user_check = mysql_num_rows($user_select);
    
    if ($user_check == 0)
    {
    	mysql_query("INSERT INTO User (User_name) VALUES ('$name')") or die(mysql_error());
    	
    	$new_user = mysql_query("SELECT * FROM User WHERE User_ID = LAST_INSERT_ID()");
    	
    	$fetch_new_user = mysql_fetch_array($new_user);
    	
    	mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
    	             VALUES ('$fetch_new_user[User_ID]','$msg',NOW())") or die(mysql_error());
    }
    
    else 
    {
    	mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
    				 VALUES ('$fetch_select[User_ID]','$msg',NOW())") or die(mysql_error());
    }
    
    $sql = mysql_query("SELECT Msg_body,Date_Time,User_name
    					FROM Messages,User
    					WHERE From_user = User_ID
    					AND Msg_ID = LAST_INSERT_ID()
    					ORDER BY Date_Time DESC") or die(mysql_error());
    			
    	while($result = mysql_fetch_array($sql))
    {
    $mydata = '<tbody id="tbody1">
    	 <tr class="highlight">
    	<td  width="30" id="bullet" align="center">
    	<a href="#" class="nohighlight">•</a></td>
    	<td width="30px" align="center" id="replyImg"><input type="image" src="css/images/reply_arrow.png" onClick="reply()"></input></td>
    	<td width="70" align="Left" id="time">'.$result["Date_Time"].'</td>
    	<td width="200" align="Left" id="from">'.$result["User_name"].'</td>
    	<td width="200" align="Left" id="to">'.$result[""].'</td>
        <td id="showMsg">'.$result["Msg_body"].'</td>
    <td width="200" align="left" id="group">'.$result["Grp_abr"].'</td>		
    </tr>
    </tbody>';
    	
    	}
    	
    		echo $mydata;
    Last edited by gits; Jul 29 '09, 08:59 AM. Reason: added code tags
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    i guess that you wanted to use setInterval() for continous execution ... or just call the timeout from the success-handler ...

    kind regards

    Comment

    • sarah aziz
      New Member
      • Sep 2007
      • 31

      #3
      How? can you show me i have been working for 2 months on this and i am getting mad

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        :) just use:

        Code:
        window.setInterval(updateMsg, 7000);
        or:

        Code:
        function updateMsg() {
            $.ajax({
                url: 'db.php',
                type: 'GET',
                success: function(data) {
                    addMessages();
                    window.setTimeout(updateMsg, 7000);
                }
            });
        }

        Comment

        • sarah aziz
          New Member
          • Sep 2007
          • 31

          #5
          Hey i am so sorry but it didn't do the trick anyother ideas
          i usually test it with 2 browser windows

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5390

            #6
            post the code that you currently use ...

            Comment

            • sarah aziz
              New Member
              • Sep 2007
              • 31

              #7
              Hi
              This is javascript
              Code:
              $(document).ready(function()
              {
                  updateMsg();
              });
              
              function updateMsg()
              {
              $.ajax({
                      url:"db.php",
                      type:"POST",
                      success:function(data){
              	alert("Hello");
                      }
              });
              setTimeout("updateMsg()",7000);
              }
              
              function addMessages()
              {
              $.ajax({
                      url:"db.php",
                      type:"POST",
                  data:"name="+$("#name").val()+"&to="+$("#user2").val()+"& cc="+$("#user").val()+"&msg="+$("#msg").val(),  
                  success:function(data)
                      {
                      $("#t1").prepend(data);}
              });
              }
              and this is php
              Code:
              $name = $_POST['name'];
              $user2 = $_POST['to'];
              $user = $_POST['cc'];
              $msg = $_POST['msg'];
              
              $user_select = mysql_query("SELECT * FROM User WHERE User_name = '$name'") 
              							or die(mysql_error());
              $fetch_select = mysql_fetch_array($user_select);
              $user_check = mysql_num_rows($user_select);
              
              if(isset($_POST['msg']) && $_POST['msg'] != '')
              {
               if ($user_check == 0)
              {
              	mysql_query("INSERT INTO User (User_name) VALUES ('$name')") or die(mysql_error());
              	
              	$new_user = mysql_query("SELECT * FROM User WHERE User_ID = LAST_INSERT_ID()");
              	
              	$fetch_new_user = mysql_fetch_array($new_user);
              	
              	mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
              	             VALUES ('$fetch_new_user[User_ID]','$msg',NOW())") or die(mysql_error());
              }
              
              else 
              {
              	mysql_query("INSERT INTO Messages(From_user,Msg_body,Date_Time) 
              				 VALUES ('$fetch_select[User_ID]','$msg',NOW())") or die(mysql_error());
               }
              }
              
              $sql = mysql_query("SELECT Msg_body,Date_Time,User_name
              					FROM Messages,User
              					WHERE From_user = User_ID
              					AND Msg_ID = LAST_INSERT_ID()
              					ORDER BY Date_Time DESC") or die(mysql_error());
              			
              	while($result = mysql_fetch_array($sql))
              {
              $mydata = '<tbody id="tbody1">
              	 <tr class="highlight">
              	<td  width="30" id="bullet" align="center">
              	<a href="#" class="nohighlight">•</a></td>
              	<td width="30px" align="center" id="replyImg"><input type="image" src="css/images/reply_arrow.png" onClick="reply()"></input></td>
              	<td width="70" align="Left" id="time">'.$result["Date_Time"].'</td>
              	<td width="200" align="Left" id="from">'.$result["User_name"].'</td>
              	<td width="200" align="Left" id="to">'.$result[""].'</td>
                  <td id="showMsg">'.$result["Msg_body"].'</td>
              <td width="200" align="left" id="group">'.$result["Grp_abr"].'</td>		
              </tr>
              </tbody>';
              	
              	}
              	
              		echo $mydata;
              Last edited by Frinavale; Jul 31 '09, 08:10 PM. Reason: Added code tags

              Comment

              • dlite922
                Recognized Expert Top Contributor
                • Dec 2007
                • 1586

                #8
                Use Firefox, then go to Tools -> Error Console to see your Javascript errors.



                Dan

                Comment

                • sarah aziz
                  New Member
                  • Sep 2007
                  • 31

                  #9
                  No errors at the error console
                  Even though i have firebug

                  Comment

                  • gits
                    Recognized Expert Moderator Expert
                    • May 2007
                    • 5390

                    #10
                    you posted the same code as the first time .... with no adaptions i suggested? so try:

                    Code:
                    function updateMsg() {
                        $.ajax({
                            url: 'db.php',
                            type: 'POST',
                            success: function(data) {
                                alert('Hello');
                                window.setTimeout(updateMsg, 7000);
                            }
                        });
                    }
                    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 ...

                    Comment

                    • sarah aziz
                      New Member
                      • Sep 2007
                      • 31

                      #11
                      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

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5390

                        #12
                        the updateMsg() function just does an XMLHttpRequest to db.php ... without sending any data ... is that your intention?

                        Comment

                        • sarah aziz
                          New Member
                          • Sep 2007
                          • 31

                          #13
                          No i want to retrieve the last data added to the database

                          Comment

                          • gits
                            Recognized Expert Moderator Expert
                            • May 2007
                            • 5390

                            #14
                            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() ...

                            Comment

                            • sarah aziz
                              New Member
                              • Sep 2007
                              • 31

                              #15
                              Hi Gits
                              I totally changed the code what do you think now it is still not working
                              javascript
                              Code:
                              	$(document).ready(function(){
                              			timestamp = 0;
                              			updateMsg();
                              			$("form#chatform").submit(function(){
                              				$.post("db.php",{
                              							message: $("#msg").val(),
                              							name: $("#name").val(),
                              							action: "postmsg",
                              							time: timestamp
                              						}, function(data) {
                              					$("#msg").empty();
                              					addMessages(data);
                              				});
                              				return false;
                              			});
                              		});
                              		function addMessages(data) {
                              			alert(data);
                              			//if($("status",data).text() == "2") return;
                              			timestamp = $("time",data).text();
                              			$("message",data).each(function(id) {
                              				message = $("message",data).get(id);
                              				$("#t1").prepend("<tr><td></td><td></td><td>"+$("name",message).text()+"</td><td></td><td>"+$("text",message).text()+"</td><td></td>");
                              			});
                              		}
                              		/*<b>"+$("name",message).text()+
                              									"</b>: "+$("text",message).text()+
                              									"<br />*/
                              		function updateMsg() {
                              			$.post("db.php",{ time: timestamp }, function(data) {
                              				addMessages(data);
                              			});
                              			setTimeout('updateMsg()', 4000);
                              		}
                              php
                              Code:
                              foreach($_POST as $key => $value)
                              {
                              	$$key = mysql_real_escape_string($value, $dbconn);
                              }
                              
                              if(@$action == "postmsg")
                              {
                              	mysql_query("INSERT INTO Messages (`Msg_body`,`Date_Time`)
                              				VALUES ('$message',".time().")");
                              }
                              
                              $messages = mysql_query("SELECT Msg_body
                              						 FROM Messages
                              						 ORDER BY id ASC");
                              if(mysql_num_rows($messages) == 0) $status_code = 2;
                              else $status_code = 1;
                              
                              echo "<?xml version=\"1.0\"?>\n";
                              echo "<response>\n";
                              echo "\t<status>$status_code</status>\n";
                              echo "\t<time>".time()."</time>\n";
                              if($status_code == 1)
                              {
                              	while($message = mysql_fetch_array($messages))
                              	{
                              		$message['Msg_body'] = htmlspecialchars(stripslashes($message['Msg_body']));
                              		echo "\t<message>\n";
                              		echo "\t\t<name>$message[From_user]</name>\n";
                              		echo "\t\t<text>$message[Msg_body]</text>\n";
                              		echo "\t</message>\n";
                              	}
                              }
                              echo "</response>";
                              Last edited by gits; Aug 3 '09, 10:10 AM. Reason: added code tags

                              Comment

                              Working...