Contenido

Como crear un chat con ajax

3 Feb

+ 9

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.

  1. Uno HTML que va a ser la base en donde montaremos el chat.
  2. Un fichero JS (Javascript) donde tendremos las llamadas necesarias para contactar con el fichero PHP.
  3. 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

Tengo una pregunta, en que parte del php esta para cambiar lo de nombre usuario y nombre de base datos etc,,,,

En el include './mysql.inc.php'; . Ahi es donde realiza la conexión de con nuestra base de datos.

un saludo.

He querio tener un chats en la pagina de la comunidad Interlinux, para tratar temas de Linux; veo todos los que ofrecen chat se van a otros temas quisiera que me qyudara a poner un chat en la comunidad; puedo en contar prestación colocar un baner en nuestras diferentes paginas de nuestra comunidad que son http://www.interlinux.info, http://www.linwx.com, linwx.org, http://www.comunidadsoftwarelibrecolombia.org
o si mejor prefiere le damos un espcio en nuestro Histingintercultura.com.
Quiero sequir los pasos que usted me indique o me asesore.
Cordialmente Hermán Lozano
Director General

Donde se define la funcion fn_call ¿?¿

Saludos,

hay alternativas a php, mysql, ajax, etc. Para hacer un Chat no es necesario “matar mosquitos a cañonazos”. Con Perl, Html, etc. es suficiente; es decir, con unos 3 ó 4 Kb. se puede hacer un Chat potentísimo y muy rápido (en tiempo real). No voy a reinventar las conocidas ventajas del singular lenguaje interpretado. Perl es compatible con todas las plataformas y sistemas; además, es más potente y rápido que ningún otro lenguaje interpretado. En fin…, vayamos al “grano”. Os pongo un enlace de la última web donde lo instalé http://www.eltrensolitario.com no castiguéis mucho el Chat. Gracias.

El desarrollo con algún ejemplo está en mi web http://www.retroaudio.es/chatbar_08.htm con velocidad del scroll sensible a la posición del mouse http://www.retroaudio.es/chatbar08.htm y otras variantes que se pueden crear, adaptar…

Espero sea útil.

hola que tal mira a mi me sale error en la linea 56 del shoutbox.php

foreach ($arr as &$row) {

bueno estoy trabajando con phptriad.
quisiera q me ayudes xfavor
rgracias
atte:
XxLuAnxX

Comentar

#

Me reservo el derecho de eliminar y/o modificar los comentarios que contengan lenguaje inapropiado, spam u otras conductas no apropiadas en una comunidad civilizada. Si tu comentario no aparece, puede ser que akismet lo haya capturado, cada día lo reviso y lo coloco en su lugar. Siento las molestias.