La capacidad de ajax para recargar secciones de la web sin necesidad de recargar toda la web, da lugar a muchas utilidades más que interesantes, desde esta página nos muestran como desarrollar un chat usando esta tecnología para insertar los comentarios.
Ejemplo
¿Que necesitamos?
Con estos ficheros ya podemos ponernos manos a la obra con el código.
Vamos a crear 3 ficheros para completar la funcionalidad.
- Uno HTML que va a ser la base en donde montaremos el chat.
- Un fichero JS (Javascript) donde tendremos las llamadas necesarias para contactar con el fichero PHP.
- Y uno PHP para realizar las insercciones y lecturas de la BD.
El fichero HTML (index.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shoutbox</title>
</head>
<body>
<h2>Shoutbox</h2>
<h3>Ejemplo</h3>
<form onsubmit="shout(); return false">
<textarea id="shoutbox" readonly="readonly"></textarea><br />
<input type="text" id="shouttext" size="120" maxlength="100" />
<input type="submit" value=" shout " id="shoutbutton" />
</form>
<script type="text/javascript" xsrc="fn.js"></script>
<script type="text/javascript" xsrc="shoutbox.js"></script>
</body>
</html>
El fichero Javascript (shoutbox.js)
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);
}
El fichero PHP (shoutbox.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);
}
?>
Solo nos quedará crear la tabla necesaria en la BD, esto lo podremos realizar usando phpmyadmin.
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;
Descargar el código: aqui
7 comentarios, 3 referencias
+
#