Chatterbox2





16
Date Submitted Thu. Mar. 1st, 2007 2:09 PM
Revision 1 of 1
Helper ushi
Tags ajax | Chat | JavaScript | PHP
Comments 3 comments
Simple chatting script to be placed on a corner of a website
Also a good example how to use ajax.

<html>
  <head>
    <title>Let's Chat</title>
    <script src="chatterbox.js" type="text/javascript" language="javascript"></script>
  </head>
  <body onLoad="javascript:getChatter();">
    <form action="" method="post" id="chatterform">
      <label>Name<br /><input type="text" name="name" id="cb_name" value="" /></label><br />
      <label>Message<br /><textarea name="message" id="cb_message" rows="4"></textarea></label><br />
      <br />
      <a href="javascript:chat();">Chatter!</a><br />
      <a href="javascript:getChatter();">Refresh</a>
    </form>
    <hr />
    <div id="chatter"></div>
    <hr />
  </body>
</html>
 

<script type="text/javascript">
  var ajax = false;
  var name = null;
  var message = null;
  var chatter = null;

  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  }

  function getChatter() {
    if (window.ActiveXObject) {
      ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }

    chatter = document.getElementById('chatter');
               
    ajax.onreadystatechange = processChange;
    ajax.open("GET", "chatter.php");
    ajax.send(null);
  }

  function chat() {
    if (window.ActiveXObject) {
      ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    name = document.getElementById('cb_name');
    message = document.getElementById('cb_message');

    ajax.onreadystatechange = processChange;
    ajax.open("GET", "chatter.php?n=" + name.value + "&m=" + message.value);
    ajax.send(null);
  }
       
  function processChange() {
    if (ajax.readyState == 4) {
      chatter.innerHTML = ajax.responseText;
    }
  }
 

<?php   
  $file = "chatter.txt";
       
  if(!file_exists($file)) { echo "Internal error."; die(); }

  if(isset($_GET['n']) && isset($_GET['m'])) {
       
    $name = strip_tags($_GET['n']);
    $message = strip_tags($_GET['m']);
               
    $new_content = (file_get_contents($file) . "\n<p><b>" . $name . "</b><br /><span>" . $message . "</span></p>");          
    file_put_contents($file, $new_content);
  }

  $content = explode("\n", file_get_contents($file));   
  $count = count($content);
  echo ($content[$count-1] . "\n" .
          $content[$count-2] . "\n" .
          $content[$count-3] . "\n" .
          $content[$count-4] . "\n" .
          $content[$count-5] . "\n");

?>
 

Juri Saltbacka

Comments

Comments Buggy ie
Thu. Mar. 1st, 2007 2:22 PM    Helper ushi
  Comments Cashing
Tue. Mar. 6th, 2007 7:06 PM    Helper albud
Comments Did not work for me
Tue. Jun. 19th, 2007 4:06 PM    Beginner stutimandal

Voting