Jump to content

Stop flickering and scrollign in PHP-based chat?


twilitegxa

Recommended Posts

I have a php-based chat room that I found online, but I would like some help on improving it. I know there is a way to stop the flickering when the page refreshes using JavaScript or something I think, but I am unsure of how to do it. I will assume this topic might need to go into the JavaScript section, but I wasn't exactly sure if someone in PHP might be able to help, so I first posted it here. But move it if it needs to me moved i guess mods. I found a chat room that does it called jenChat, but I do not know how to incorporate this into this chat room. What I want to do is stop the flickering when the chat screen refreshes and also not have the screen automatically scroll back up, which would allow users to scroll up and read previous comments, then scroll back down when they are done. Right now if they try that, in a second it scrolls back down, so they wold be unable to read any previous comments in the chat.

 

Here is what I have so far. The main page you view:

 

chatframe:

<?php

print "<iframe src='chatlog.php'  name='chatlogframe' width='350' height='400'></iframe>";

print "<br><br>";

print "<iframe src='submit.php' width='380' height='180' frameborder='0'scrolling='no'></iframe><br><br>";

?>

 

The page that shows the chat messages:

 

chatlog.php:

<?php

include "connect.php";

$getnummessages="SELECT COUNT(*) as messagecount from chatmessages";

$getnummessages2=mysql_query($getnummessages) or die("blah");

$getnummessages3= mysql_result($getnummessages2, 0);

if($getnummessages3>21)

{

  // $startrow=$getnummessages3-20;
  $startrow=1;

}

else

{

  $startrow=1;

}

$getmsg="SELECT name, message from chatmessages order by postime ASC limit $startrow,$getnummessages3";

$getmsg2=mysql_query($getmsg) or die(mysql_error());

while($getmsg3=mysql_fetch_array($getmsg2))

{
  $message = $getmsg3['message'];
  $message=Smiley($message); //Smiley faces

   print "<font color='red'><b>$getmsg3[name]:</b></font> $getmsg3[message]<br>";



}



function Smiley($texttoreplace)

{

    $smilies=array( 

    

    

    '' => "<img src='images/smile.gif'>",

    ':blush' =>"<img src='images/blush.gif'>",

    ':angry' =>"<img src='images/angry.gif'>",

    ''=>     "<img src='images/shocked.gif'>",  

    'fuck'=>"$#$%",

    'Fuck'=>"&$#@"

  



    );



    $texttoreplace=str_replace(array_keys($smilies), array_values($smilies), $texttoreplace);

    return $texttoreplace;

}

?>

<script>

  setTimeout("window.location.replace('chatlog.php')",2000);



</script>

 

And here is the jenChat example that shows how to stop the flickering and to the scrolling problem:

 

chat.php:

<?php
  session_start();
  if(!$_SESSION['jenChat_UserID']){
    header("Location: ./login.php");
    exit;
  }
  else if(date("YmdHis",time() - 5) > $_SESSION['jenChat_Prevtime']){
    header("Location: ./login.php?logout=true");
    exit;

  }
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  <head>
    <title>jenChat</title>
    <style type="text/css">
      #chatContents{height:300px; width:200px;}

 

init.php:

<?php
  session_start();
  
  /*
   * replace the parameters used here with the appropriate information
   * for your system.
   */
  $dbhandle = mysql_connect("server","user","password");
  mysql_select_db("database_name");

    
  /*
   * IMPORTANT: magic quotes are bad. Ideally, you should turn them off 
   * in your php.ini, but if you are unable to, the code below will fix 
   * the $_POST array for you.
   * 
   * See http://www.php.net/manual/en/security.magicquotes.php
   * 
   * If you aren't using prepared statements (mysqli, Pear:DB) or manually  
   * escaping every variable that goes into a query, you are asking to get
   * pwned. For maximum portability, jenChat uses mysql_real_escape_string,
   * but prepared statements are generally the way to go.
   * 
   * If you didn't understand that last paragraph (or even if you
   * did), read up on SQL Injection and why you need to worry about it.
   *   
   * http://www.unixwiz.net/techtips/sql-injection.html
   * 
   * OK, carry on
   */
   
  if(get_magic_quotes_gpc()){
    $_POST = array_map('stripslash', $_POST);
  }
  function stripslash($value){
    if(is_array($value))
      return array_map('stripslash', $value);
    else
      return stripslashes($value);

 

post.php:

<?php
  require_once('init.php');

  /* make sure the person is logged in. */
  if(!isset($_SESSION['jenChat_UserID']))
    exit;
  
  /* make sure something was actually posted. */
  if(sizeof($_POST)){
    $expiretime = date("YmdHis",time() - 30);

    /* delete expired messages. */
    mysql_query("DELETE FROM jenChat_Messages 
                 WHERE Posted <= '" . $expiretime . "'"); 
    /* delete inactive participants. */
    mysql_query("DELETE FROM jenChat_Users 
                 WHERE LastUpdate <= '" . $expiretime. "'"); 
    /* post the message. */
    mysql_query("INSERT INTO jenChat_Messages (UserID,Posted,Message)
                 VALUES(
                  " . $_SESSION['jenChat_UserID'] . ",
                  '" . date("YmdHis", time()) . "',
                  '" . mysql_real_escape_string(strip_tags($_POST['message'])) . "'
                 )");
  
    header("Location: post.php");
    exit;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  <head>
    <script type="text/javascript"><!--
      if(parent.resetForm)
        parent.resetForm();
      //-->
    </script>
  </head>
</html>

 

thread.php:

<?php
  require_once('init.php');

  /* make sure the person is logged in. */
  if(!isset($_SESSION['jenChat_UserID']))
    exit;

  $currtime = date("YmdHis",time());

  /* maintains this user's state as active. */
  mysql_query("UPDATE jenChat_Users SET LastUpdate = '" . $currtime . "'
                WHERE UserID = " . $_SESSION['jenChat_UserID']);

  /* grab any messages posted since the last time we checked.
  Notice we say >= and <. This is to guarantee that we don't miss any
  messages that are posted at the same instant this query is
  executed.*/
  $sql = "SELECT Message,UserName
          FROM jenChat_Messages
          INNER JOIN " . "jenChat_Users
            ON jenChat_Messages.UserID = jenChat_Users.UserID 
          WHERE Posted >= '" . $_SESSION['jenChat_Prevtime'] . "' 
            AND Posted < '" . $currtime . "'
          ORDER BY Posted";
  $res = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  <head></head>
  <body>
  <?
    if(mysql_num_rows($res)){
      echo '<div id="contents">';
      while($row = mysql_fetch_array($res)){
        echo '<div><strong>' .
              htmlspecialchars($row['UserName']) . ': </strong>' .
              htmlspecialchars($row['Message']) . '</div>';
      }
      echo '</div>';
    }
    $_SESSION['jenChat_Prevtime'] = $currtime;

  ?>
  </body>
</html>[pre]
  }
?>[/pre][pre]
  }
?>[/pre][pre]
    </style>
  </head>
  <body>
    <h1>jenChat</h1>

    <a href="login.php?logout=true">Logout</a><br />

    <iframe id="chatContents" name="chatContents" src="contents.html"></iframe>

    <form target="post" method="post" action="post.php">
      <input type="text" name="message" id="message" style="width: 250px" />
      <input type="submit" value="Send" class="submit" />
    </form>

    <iframe id="post" name="post" src="post.php"
      style="width: 0px; height: 0px; border: 0px;"></iframe>
    <iframe id="thread" name="thread" src="thread.php"
      style="width: 0px; height: 0px; border: 0px;"></iframe>
  </body>
</html>[/pre]

 

This was the Javascript in the jenChat that is in the post.php page that is supposed to stop the flickering:

 

[pre]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  <head>
    <script type="text/javascript"><!--
      if(parent.resetForm)
        parent.resetForm();
      //-->
    </script>
  </head>
</html>[/pre]

 

This is the Javscript that is sppsoed to refresh the page and is supposed to go into thread.php:

 

[pre]<script type="text/javascript"><!--
  if(parent.insertMessages && document.getElementById("contents"))
    parent.insertMessages(document.getElementById("contents").innerHTML);
  
  setTimeout("getMessages()",1000); //poll server again in one second

  function getMessages(){
    document.location.reload();
  }
  //-->
</script>[/pre]

 

And this last part goes into chat.php:

 

[pre]<script type="text/javascript"><!--
  var cDocument;
  var cWindow;

  window.onload = chat_init;

  function chat_init(){
    var chatContents = document.getElementById("chatContents");

    //set up a reference to the window object of the IFRAME
    if(window.frames && window.frames["chatContents"]) //IE5, Konq, Safari
      cWindow = window.frames["chatContents"];
    else if(chatContents.contentWindow) //IE5.5+, Moz 1.0+, Opera
      cWindow = chatContents.contentWindow;
    else //Moz < 0.9 (Netscape 6.0)
      cWindow = chatContents;

    //set up a reference to the document object of the IFRAME
    if(cWindow.document) //Moz 0.9+, Konq, Safari, IE, Opera
      cDocument = cWindow.document;
    else //Moz < 0.9 (Netscape 6.0)
      cDocument = cWindow.contentDocument;
  }
  function insertMessages(content){
    //place the new messages in a div
    var newDiv = cDocument.createElement("DIV");
    newDiv.innerHTML = content;

    //append the messages to the contents
    cDocument.getElementById("contents").appendChild(newDiv);

    //scroll the chatContents area to the bottom
    cWindow.scrollTo(0,cDocument.getElementById("contents").offsetHeight);
  }
  function resetForm(){
    document.getElementById("message").value = "";
    document.getElementById("message").focus();
  }//-->
</script>[/pre]

 

Here is the link to the jenChat tutorial: http://code.jenseng.com/jenChat/ . Please if anyone can help me with these two problems. I had trouble getting my messages to post and view correctly with jenChat, which is why I'm not using it. But, the one I'm using has no problems with that. i just need to stop the flicking and scrolling issue so that people can view the previous messages while new ones are begin posted and while the page refreshes. Can anyone help?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.