« Previous entry | Next entry » Browse > Snippets

Skip to comments (41) simple shoutbox
Posted by Erik on Jan 02 2006 @ 13:18  :: 12296 unique visits

A simple shoutbox using XMLHTTPRequests.


example here


These scripts are used:
javascript to php function call.
mysql functions.


the html:
CODE: HTML
<form onsubmit="shout(); return false">
  <textarea id="shoutbox" readonly="readonly"></textarea><br />
  <input type="text" id="shouttext" size="100" maxlength="100" />
  <input type="submit" value="&nbsp;shout&nbsp;" id="shoutbutton" />
</form>

<script type="text/javascript" src="fn.js"></script>
<script type="text/javascript" src="shoutbox.js"></script>


shoutbox.js
CODE: JAVASCRIPT
var shoutbox    = document.getElementById('shoutbox');
var shouttext   = document.getElementById('shouttext');
var shoutbutton = document.getElementById('shoutbutton');
var lastupdate  = 0;
var updatetime  = 1000; // update every 1 second
var name        = null;

// this file will handle the fn calls
fn_url   = 'shoutbox.php';
fn_debug = false;

// make the width of the shoutbox equal to the width of the input field + the button
shoutbox.style.width  = parseInt(shouttext.offsetWidth) +
                        parseInt(shoutbutton.offsetWidth) + 'px';
shoutbox.style.height = '200px';

shoutbox.value = 'click here to join...';
setTimeout(update, 10);


shouttext.onfocus = function() {
  if (name == null) {
    name = prompt('enter your display name', '');
   
    if (name == null) {
      shouttext.blur();
    } else {
      fn_call('event', false, name, 'joined the shoutbox');
   
      shouttext.value = '';
      shouttext.focus();
    }
  }
}


window.onunload = function() {
  if (name != null) {
    fn_url = 'shoutbox.php';
    fn_call('event', false, name, 'left the shoutbox');

    // withoud this the fn_call will fail
    alert('leaving shoutbox...');
  }
}


function shout() {
  var str = shouttext.value;
 
  if (str != '') {
 
    if (str == '/clear') {
      shoutbox.value = '';
    }
   
    else if ((str.indexOf('/name') == 0) ||
             (str.indexOf('/nick') == 0)) {
      var oldname = name;
      name = prompt('enter your display name', '');

      if (name == null) {
        name = oldname;
      } else if (name != oldname) {
        fn_call('event', false, oldname, 'changed his name to: '+name);
      }
    }
   
    else {
      fn_call('shout', false, name, shouttext.value);

      // stop people from speaking to fast
      shoutbutton.disabled = true;
      setTimeout('shoutbutton.disabled = false;', 500);
    }
   
    shouttext.value = '';
  }
}


function updateresult(arr) {
  lastupdate = arr[0];
  arr        = arr[1];

  for (var i = arr.length - 1; i >= 0; i--) {
    shoutbox.value += '\n' + arr[i];
  }

  // change the update time if there is nothing heapening
  if (arr.length == 0) {
    updatetime += (updatetime > 5000) ? 0 : 500; // max 5 sec
  } else {
    // scroll to the bottom
    shoutbox.scrollTop = shoutbox.scrollHeight * 25; // IE fix
    updatetime = 1000;
  }

  setTimeout(update, updatetime);
}


function update() {
  fn_call('update', updateresult, lastupdate);
}


shoutbox.php
CODE: PHP
<?

include './fn.inc.php';


// make sure this is a single non empty line
function validate($str) {
  if (strpos($str, "\n") !== false) {
    die();
  }

  $str = trim($str);

  if (empty($str)) {
    die();
  }

  return $str;
}


function insertline($name, $str, $type) {
  $name = validate($name);
  $str  = validate($str);
 
  include './mysql.inc.php';

  // I don't use the mysql UNIX_TIMESTAMP() function because our web and sql server
  // don't alwais have the exsact same time which would make you miss some messages or get some twice.
  mysql_do_query('INSERT INTO shoutbox (time, name, type, text) VALUES('.time().', "'.$name.'", '.$type.', "'.$str.'")');
}


function fn_event($name, $str) {
  insertline($name, $str, 1);
}


function fn_shout($name, $str) {
  insertline($name, $str, 0);
}


function fn_update($last) {
  include './mysql.inc.php';

  $query = "
    SELECT id, time, name, type, text
    FROM shoutbox
    WHERE id > $last
    ORDER BY time DESC
    LIMIT 100
   "
;
  $arr = mysql_rows($query);
 
  foreach ($arr as &$row) {
    $last = max($last, $row[0]);

    $n = '['.date('h:i:s', $row[1]).'] ';
   
    if ($row[3] == 0) {
      $row = $n.'<'.$row[2].'> '.$row[4];
    } else {
      $row = $n.$row[2].' '.$row[4];
    }
  }

  return array($last, $arr);
}

?>


mysql table layout
CODE: SQL
CREATE TABLE shoutbox (
  id   int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  time int(10) UNSIGNED NOT NULL DEFAULT '0',
  name varchar(16)      NOT NULL DEFAULT '',
  type int(10) UNSIGNED NOT NULL DEFAULT '0',
  text varchar(100)     NOT NULL DEFAULT '',
  PRIMARY KEY (id)
) TYPE=MyISAM;

41 comments posted so far
Add your own »

1. On Jan 23 2006 @ 07:06 Saivert wrote:

It might even be possible to create an AJAX based IRC client if you code a PHP backend that links with a IRC bot.

2. On Jan 26 2006 @ 03:06 guest wrote:

ssxsxsxsx

3. On Jan 30 2006 @ 23:28 guest wrote:

hope this works

4. On Feb 02 2006 @ 20:42 aNieto2k wrote:

I have a problem with arr variable.

Error: arr has no properties
Archivo de origen: http://localhost/CHAT/shoutbox.js
Línea: 86

5. On Mar 01 2006 @ 20:36 guest wrote:

what's up with "include './mysql.inc.php';" and "include './fn.inc.php';" ?

6. On Mar 01 2006 @ 23:13 Erik wrote:

fn.inc.php is for javascript to php function calls and mysql.inc.php contains some usefull database functions and connects to the mysql database.

7. On Mar 15 2006 @ 05:05 guest wrote:

wow kool shoutbox :)

8. On Mar 15 2006 @ 17:30 guest wrote:

this is awesome!

9. On Apr 11 2006 @ 20:05 guest wrote:

Do I have to create the 2 files and put them in a folder? add tables to the MYsql DB? and then add the HTML text to the Index page?

OR Is there some way to add everything in the index page?

thanks

10. On Apr 12 2006 @ 10:18 guest wrote:

cool

11. On Apr 13 2006 @ 22:58 TestUser wrote:

wastes too much space imo

12. On Apr 26 2006 @ 06:30 Ralph wrote:

Im very disappointed. This script seems excellent but this tutorial is horrible. It worked after I made some adjustments in the script but its spitting out incorrect content for the ID, TIME, TYPE (look for yourself http://www.project07.com/shout).

please help me out or redo this tutorial

13. On Apr 27 2006 @ 20:11 Unadrien wrote:

Without any knowledges at all within Ajax, mySQL, php and javascript I made this work! Im impressed that i solved it without any big problems. I borrowed a friends server wich could handle php and mySQL, there I also loaded up the database. Thank you for these scripts!

14. On Jun 29 2006 @ 15:18 guest wrote:

:-) good in deed

15. On Jul 11 2006 @ 02:54 Prism wrote:

Hey, havin some problems with this system.

I cant get it to display the chat or save it to the database, followed your guide to the letter.

If you wana have a look, http://shite.prism27.net/shout

cheers,

- Prism

16. On Jul 11 2006 @ 03:08 Prism wrote:

Kinda found the problem. This is an extract from my error_log file:

PHP Parse error:  parse error, unexpected '&', expecting T_VARIABLE or '$' in /home/.../shite/shout/shoutbox.php on line 56

17. On Jul 11 2006 @ 03:11 Prism wrote:

Sorry to spam, found the error.

Change:
CODE: PHP
function fn_update($last) {
  include './mysql.inc.php';

  $query = "
    SELECT id, time, name, type, text
    FROM shoutbox
    WHERE id > $last
    ORDER BY time DESC
    LIMIT 100
   "
;
  $arr = mysql_rows($query);
 
  foreach ($arr as &$row) {
    $last = max($last, $row[0]);

    $n = '['.date('h:i:s', $row[1]).'] ';
   
    if ($row[3] == 0) {
      $row = $n.'<'.$row[2].'> '.$row[4];
    } else {
      $row = $n.$row[2].' '.$row[4];
    }
  }

  return array($last, $arr);
}

?>


to
CODE: PHP
function fn_update($last) {
  include './mysql.inc.php';

  $query = "
    SELECT id, time, name, type, text
    FROM shoutbox
    WHERE id > $last
    ORDER BY time DESC
    LIMIT 100
   "
;
  $arr = mysql_rows($query);
 
  foreach ($arr as $row) {
    $last = max($last, $row[0]);

    $n = '['.date('h:i:s', $row[1]).'] ';
   
    if ($row[3] == 0) {
      $row = $n.'<'.$row[2].'> '.$row[4];
    } else {
      $row = $n.$row[2].' '.$row[4];
    }
  }

  return array($last, $arr);
}

?>


Sorry for the triple post!

18. On Jul 26 2006 @ 16:44 guest wrote:

so for dreamweaver what is the code for the shoutbox?

19. On Aug 07 2006 @ 12:27 Deepdrone wrote:

^There is no code for Dreamweaver. Use plain editor instead.

And thanks to the Labs for the utility!

20. On Aug 17 2006 @ 19:46 guest wrote:

me da este error, alguien ayudeme porfavor.


PHP Parse error:  parse error, unexpected '&', expecting T_VARIABLE or '$' in /home/.../shite/shout/shoutbox.php on line 56

21. On Aug 22 2006 @ 06:49 guest wrote:

test

22. On Sep 02 2006 @ 21:26 ricky wrote:

have a look at my site...
www.jaat-union.uni.cc
which type code do i use for it...
i used html...
the shoutbox appears to my forum...but its not showing shouts...

23. On Sep 15 2006 @ 05:56 guest wrote:

&#12354;&#12354;

24. On Jun 28 2007 @ 11:26 guest wrote:

test

25. On Jul 20 2007 @ 05:57 guest wrote:

&#65364;&#65367;&#12428;&#12390;&#65362;

26. On Aug 09 2007 @ 12:55 guest wrote:

aaaa

27. On Sep 04 2007 @ 08:01 Bobo wrote:

Giggity!

28. On Sep 16 2007 @ 23:15 guest wrote:

mooo

29. On Sep 30 2007 @ 01:32 guest wrote:

dezrt.co.nr

30. On Oct 30 2007 @ 02:53 guest wrote:

s.a

31. On Nov 14 2007 @ 08:02 guest wrote:

www.gevrip.5u.com     free stuff and goods

32. On Nov 14 2007 @ 20:52 Whinnie26 wrote:

hi,
can you use the javascript code on dreamweaver(p.s i'm only 12)

33. On Feb 23 2008 @ 16:32 bbb wrote:

there seems to be a javascript error preventing the code to work.. does somebody know how to solve that?

34. On Feb 23 2008 @ 16:33 bbb wrote:

what i forgot in the comment above: to see what i mean just click on "show example" above.. it doesn't work in any of my browsers..

35. On Jun 29 2008 @ 18:06 guest wrote:

gbhgdf

36. On Jul 06 2008 @ 17:00 DrunkenDragon wrote:

The shout didn't show up

Drunken Dragon

37. On Jul 06 2008 @ 17:00 Drunkendragon wrote:

Uhh... even comment didn't show up http://drunkendragon.cn

38. On Aug 09 2008 @ 05:19 priya wrote:

Anyone bought from www.belrion.com before ? heard they are a paypal world seller and are macfee secured. Appreciate some feedback from anyone ^^
<a href  = http://www.belrion.com/en/ffxi.htm > buy ffxi</a><br>
<a href  = http://www.belrion.com/en/eq.htm> buy eq flat </a><br>
<a href  = http://www.belrion.com/en/wow.htm> cheap wow gold</a><br>
<a href  = http://www.belrion.com>  LOTR gold</a><br>
<a href  = http://www.belrion.com/en/sell.htm>buy aoc gold</a><br>
<a href  = http://www.belrion.com/en/l2.htm> buy L2 adena</a><br>
<a href  = http://www.belrion.com/en/gamesvr.php?cid=1&gid=3&sid=10 >buy gils</a><br>
<a href  = http://www.belrion.com/en/eq.htm >cheap gold wow</a><br>

39. On Sep 14 2008 @ 13:58 guest wrote:

where do i put the mysql table layout??

40. On Oct 26 2008 @ 15:07 eusouobob wrote:

<META HTTP-EQUIV=Refresh CONTENT="10; URL=enteredtopichere.php">

Add a new comment

Name:
Password: (leave empty for anonymous comment)
 
View formatting tags Comment: