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: I expect 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 .

Member Avatar for jmichae3

mysql database? USING JAVASCRIPT-AJAX? only if you actually pass real data back and forth, such as XML or through forms or something.

setTimeout is provided by the browser (it's not really in the javascript specification) and has nothing to do with PHP, nor will it interface with PHP or anything else since it executes in javascript space.

AJAX, if it's true to its name, means Asynchronous Javascript and XML and by that it means that it is supposed to send XML back and forth to PHP. some of them are simply DHTML libraries with the word "AJAX" slapped on it. hard to find one that really is AJAX.

if you want something to happen every second, you need hosting that supports cron jobs. you then need to create a job that fires off the mysql command-line query tool (use the whole path you get from support folk) and use all the command-line switches you need to use.

know that with high frequency cron jobs, you can get kicked off your hosting, depending on the vendor (you're supposed to be low-bandwidth on shared hosting).

there are alternatives to using infinitesimal cron jobs that can get you kicked off your hosting, I have discovered. VOILA! the event-driven/on-demand method!
any DELETEs, UPDATEs, and any other database maintenance functions can be peformed without the need for cron jobs - at the instant the user visits the web page - on demand. and it's best.

DB maintenance should be done at the beginning of the page, before anything is displayed as a web page.

when you think about it, every visitor will be up-to-date.

as an alternative, you can make a gen-textarea-content.php file whose only purpose is to do the query and generate the content for the textarea control (you will have to stripslashes() on the database output for <textarea></textarea> because of the various quote types). you can use some php like <textarea><?php include 'gen-textarea-content.php'; ?></textarea> or simply just put your php code in there or do it as a function...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.