5 Replies - 1087 Views - Last Post: 04 November 2011 - 12:46 PM

#1 narekm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 23-March 11

Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 09:18 AM

Hello there. I am sooo despared since I cant make this work here is what I have in my logged_in.php file .
<html>
    <?php  echo "Welcome: "."<b>".$_SESSION["username"]."<b/>";  ?>
    <head>    
        <div id="ajax"></div>
       
                            <script type="text/javascript">
                      
                        function createXMLHttpRequest(){
                            var XMLHttpRequestObject=false;
                        
                        if(window.XMLHttpRequest)
                        {
                                       
                                      XMLHttpRequestObject=new XMLHttpRequest();
                                       return XMLHttpRequestObject;
                                 
                        } // 
                        else{
                                    if(window.ActiveXObject)
                                    {
                                    XMLHttpRequestObject=ActiveXObject("Microsoft.XMLHTTP");
                                    return XMLHttpRequestObject;
                                    }else{
                                       return false;
                                    }// End "else"  statement

                            } // End of the last "else"  statement
                        
                      }   //  End "createXMLHttpObject()" function
                      
                      HttpObject=createXMLHttpRequest();
                      //-----------------------------------------------------------------
                      function insertMessages(){
                      HttpObject.onreadystatechange=function(){
                          if(HttpObject.readyState==4 && HttpObject.status==200){
                              
                                   document.getElementById("ajax").innerHTML="";
                                    document.getElementById("ajax").innerHTML+=HttpObject.responseText;

                                  }


                              }

                                        HttpObject.open("GET","ajax_response.php",true);
                                        HttpObject.send();
                           
                      } // End  "insertMessages()" function
                     // insertMessages();
                      setTimeout("insertMessages()",1000);
                      // The below is the original "insertData()" function
                      // ------------------------------------------------------------------------
                      function insertData(user,time,message){
                      HttpObject.onreadystatechange=function(){
                          if(HttpObject.readyState==4 && HttpObject.status==200){
                              
                             // document.getElementById("ajax").innerHTML=HttpObject.responseText;
                             // document.getElementById("textarea").value+=HttpObject.responseText;
                             document.getElementById("textarea").value="";
                                    document.getElementById("textarea").value+=HttpObject.responseText;

                              
                          }
                          
                          
                      }
                    
                                HttpObject.open("GET","ajax_response.php?user="+user+"&time="+time+"&message="+message,true);
                                HttpObject.send();
                                   document.getElementById("text").value="";
                      } // End  "insertData()" function
               
                  // ------------------------------------------------------------------------
                    </script> <!--  End  The first script tag for  Ajax related functions  -->
                    
                    
        <script>
            var SESSION="<?php echo $_SESSION["username"]; ?>";
          function currentTime(){
              
           var date=new Date();
           var hours=date.getHours();
           var minutes=date.getMinutes();
           var seconds=date.getSeconds();
           var fullTime=hours+":"+minutes+":"+seconds;
            
            return fullTime;

              
          } // End "currentTime()"
            function addText(){
              
                document.getElementById("textarea").value+=SESSION+"  "+currentTime()+'\n';
                document.getElementById("textarea").value+=document.getElementById("text").value+'\n';     
            }
            
            function send(){
                if(document.getElementById("text").value!=""){
                addText();
                insertData(SESSION,currentTime(),document.getElementById("text").value);
            }
            } //  End "send()"  function
            
            
           
            
        </script>

                               

            
                    <style> #textarea { background-color:#F3F3F3;}</style>
            
        
        
    </head>
    <body>

    
        <TEXTAREA id="textarea" COLS="80" ROWS="20"   ></TEXTAREA><br/><br/>
        <input type="text" id="text" name="text"   size="96"> 
        <input type="button" value="Send" name="submit"  onclick="send()"> 
       

    </body>
</html>




And the request as I hope you saw is gonna go to ajax_response.php file. And inside that file I have
    <?php

                  //   PHP  Configuration
    defined("DB_HOST") ?      null: define("DB_HOST","localhost");
    defined("DB_USER")   ?    null: define("DB_USER","root");
    defined("DB_PASS")   ?    null: define("DB_PASS","");
    defined("DB_NAME")   ?    null: define("DB_NAME","livechat");

    // 1 . Creating the connection
      $connection=mysql_connect(DB_HOST,DB_USER,DB_PASS);
      if(!$connection){
          die("Couldnt create a database connection".  mysql_error());

      }// End "if"  for  creating connection
      // 2. Selecting  a database
      $selected_db=mysql_select_db(DB_NAME,$connection);
      if(!$selected_db){
          die("Could not select the database:".mysql_error());


      }//  End "if"   for selecting a database
      // 3. Perform query to the selected database
      if(isset($_GET["user"]) && isset($_GET["time"]) && isset($_GET["message"])){ //checking to see if the all $_GET variables have been set 
          $user=$_GET["user"];
          $time=$_GET["time"];
          $message=$_GET["message"];
    $query="INSERT INTO chat(user,time,message) VALUES('{$user}','{$time}','{$message}')";
    $result=mysql_query($query,$connection);
    $query="SELECT*FROM chat";
    // 4. Handling with the returned data
    $mysql_all_table=mysql_query($query,$connection);
    $row_number=mysql_num_rows($mysql_all_table);
      
    if($row_number>10){
  
                  //  Things for "ten_counter"
         $query="SELECT*FROM ten_counter WHERE id=1";
          $result=mysql_query($query,$connection);
          $fetched=mysql_fetch_array($result);
         $ten_counter=$fetched["ten_counter"];// 1
    
        // End things for "ten_counter"
        
        $ids_to_delete=10*$ten_counter;
        $query="DELETE FROM chat WHERE id<'{$ids_to_delete}'";
        $deleted_rows=mysql_query($query,$connection);
        if(!$deleted_rows){ die("Couldnt perform the query".mysql_error());}
  
                   $ten_counter++;
    mysql_query("UPDATE ten_counter SET ten_counter='{$ten_counter}' WHERE id=1");
      
    }// Delete 10 rows
       } //  End the "if"  for checking to see if the all $_GET variables have been set 
   function loadMessages(){
        $query="SELECT*FROM chat ORDER BY id ASC";
        $result=mysql_query($query);
        if(!$result){
            die("Query FAILED!!!".mysql_error());
        }
       $chat=array();
       while($row=mysql_fetch_array($result)){
        //array_push($chat,$row["user"]." ".$row["time"]."\n".$row["message"]." "."\n");
       echo $row["user"]." ".$row["time"]."\n".$row["message"]." "."\n";
           
       }
  
    }//   End  "loadMessages()" function
    loadMessages();
        

    //  5. Closing the connection
    mysql_close($connection);


    ?>


My question is why setTimeout("insertMessages()",1000); doesnt work : Iexpect it every 1 second go to the database take all the rows and come and output in my text area so that people that are chatting will get the answers instantly.. I hope you understood my question ..
And please I really need your help .. Deeply appreciate your time spent on this .

This post has been edited by Dormilich: 04 November 2011 - 10:07 AM
Reason for edit:: fixed code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Cant make setTimeout() AJAX work in my PHP

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 947
  • View blog
  • Posts: 2,356
  • Joined: 15-February 11

Re: Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 09:26 AM

Use code tags instead of quotes. It's actually on the right of the quote button.

You're going to kill your bandwidth like that. There's also a possibility that it takes more than a second to fetch the data causing a backup of request and responses.

Check the error console for any message your Javascript emits.
Was This Post Helpful? 0
  • +
  • -

#3 narekm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 23-March 11

Re: Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 09:36 AM

The process of killing is another matter .This is a test task for me . But why this dostn work ???
My question is one more time that why setTimeout("insertMessages()",1000); doesn output apdated rows in mysql every 1 second as given as an argument ???
Was This Post Helpful? 0
  • +
  • -

#4 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 947
  • View blog
  • Posts: 2,356
  • Joined: 15-February 11

Re: Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 10:01 AM

If you had checked your error console like I said you would have seen that you can't access DOM elements before they are created. Let's say that the response actually came back before the page was completely loaded then this statement (document.getElementById("ajax")) would fail thus causing your Javascript to fail.

Don't start the timer until the document has loaded. Look into the onload event. Word to the wise...learn to utilize your error console. It will tell you a lot about what's happening with your code.
Was This Post Helpful? 1
  • +
  • -

#5 narekm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 23-March 11

Re: Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 10:41 AM

Thank you very much . So I took the setTimeout("insertMessages()",1000); inside the "send" function(which triggers when we click on the send button) and everything works as i expected ...despite the code as you said is very ineffective . Please could you pinpoint other things thay you really didnt like about my code ?
Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,548
  • Joined: 23-August 08

Re: Cant make setTimeout() AJAX work in my PHP

Posted 04 November 2011 - 12:46 PM

This is a Javascript question, not PHP, so I'll move it to the Javascript forum.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1