Enlace:
http://zital.no-ip.org/txat/
Licencia: LGPL
http://www.gnu.org/licenses/lgpl.html
Notas:
- Tabla: id int(1), comentario text, data int(1), primary key(id)
- La fecha se guarda como mktime para luego poder formatearlo como querais.
- Se mira el id del ultimo span. para saber si hay nueva entrada.
- Se muestran los ultimos 50 comentarios.
- Eliminado el boton enviar y el form.
- Libreria de animaciones jquery,+ su plugin para los colores: color.js
- Libreria shortcut para controlar la pulsacion de teclas.
- Probado en: Konqueror, Firefox, Opera, Internet explorer. En Safari si envia el mensaje pero no actualiza, no se si sera culpa de windows :S
Arreglado:
- repeticiones del mismo comentario.
Enlaces de interes:
http://www.forosdelweb.com/f77/zital...ghlight=zitalk http://www.forosdelweb.com/f77/zital...ghlight=zitalk http://www.forosdelweb.com/f77/minic...ghlight=zitalk
index.php
Código PHP:
<?php
function Connect($host,$user,$passwd,$db)
{
if(!($link=mysql_connect($host,$user,$passwd)))
{
echo "Error connecting to DDBB.";
exit();
}
if(!mysql_select_db($db,$link))
{
echo "Error in DDBB selection.";
exit();
}
return $link;
}
function maxId()
{
$select="select max(id) from chat";
$select=mysql_query($select);
return mysql_result($select,0,0);
@mysql_free_result($select);
}
$link=Connect("host","usuario","password","DB_name");
// sending comments
if($_GET["Write"]=="yes")
{
$max=maxId()+1;
$date=mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
$comment=htmlentities(utf8_decode($_REQUEST["comment"]));
//
$insert="insert into chat values(".$max.",'".$comment."',".$date.")";
if(trim($_REQUEST["comment"])!=NULL)
{
$insert=mysql_query($insert);
}
mysql_close($link);
exit();
}
// reading comments
elseif($_GET["Read"]=="yes")
{
header("Cache-Control: no-store, no-cache, must-revalidate");
$max=maxId();
if($max<50)
{
$max=0;
}
else
{
$max=$max-50;
}
$select="select id,comentario,data from chat order by id asc limit ".$max.",50";
$select=mysql_query($select);
while($row = @mysql_fetch_array($select))
{
if($row["id"]!=NULL)
{
$date=date("Y/m/d - H:i:s",$row["data"]);
echo "<span id=".$row["id"]."><strong>".$date.":</strong> ".utf8_encode($row["comentario"])."</span><br />";
}
}
@mysql_free_result($select);
mysql_close($link);
exit();
}
// reading last comments
elseif($_GET["ReadLast"]=="yes" && $_GET["id"]!=NULL)
{
header("Cache-Control: no-store, no-cache, must-revalidate");
$id=$_GET["id"];
$max=maxId();
//
$limit1=$id;
$limit2=$max-$id;
//
$select="select id,comentario,data from chat order by id asc limit ".$limit1.",".$limit2;
$select=mysql_query($select);
while($row = @mysql_fetch_array($select))
{
if($row["id"]!=NULL)
{
$date=date("Y/m/d - H:i:s",$row["data"]);
echo "<span id=".$row["id"]."><strong>".$date.":</strong> ".utf8_encode($row["comentario"])."</span><br />";
}
}
@mysql_free_result($select);
mysql_close($link);
exit();
}
elseif($_GET["MaxId"]=="yes" && $_GET["id"]!=NULL)
{
header("Cache-Control: no-store, no-cache, must-revalidate");
$id=$_GET["id"];
$max=maxId();
echo $max;
@mysql_free_result($select);
mysql_close($link);
exit();
}
?>
Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1;"/>
<title>AJAX Chat</title>
<style type="text/css">
body
{
background-color: #C0C0C0;
color: #000000;
font-size: 13px;
}
input
{
font-size: 12px;
}
#chat
{
border: 1px solid #000000;
background-color: #F0F0F0;
height: 200px;
width: 800px;
overflow: auto;
padding: 8px;
}
</style>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/color.js"></script>
<script type="text/javascript" src="js/shortcut.js"></script>
<script type="text/javascript">
// cada 2,5 segundos se verifican nuevas entradas en la bbdd
setInterval("ajaxLasId()",2500);
// al pulsar enter se envia el comentario
shortcut.add("enter",function() {
ajaxWrite();
},{
'type':'keydown',
'propagate':true,
'target':document
});
</script>
</head>
<body>
<div>
<img src="img/loading.gif" style="display:none" alt="loading..."/>
<p>
<input type="text" id="comentario" size="100" maxlength="100"/>
</p>
</div>
<div id="chat">
</div>
<div>
<a href="http://www.forosdelweb.com/f77/zitalk-version-2-1-beta-litle-ajax-chat-545601/">Codigo fuente</a>
<br />
Licencia LGPL: <a href="http://www.gnu.org/licenses/lgpl.html">http://www.gnu.org/licenses/lgpl.html</a>
</div>
<script type="text/javascript">
ajaxRead();
document.getElementById("comentario").focus();
</script>
</body>
</html>
ajax.js
Código:
function ajaxFunction()
{ var xmlHttp;
try { xmlHttp=new XMLHttpRequest();return xmlHttp; }
catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");return xmlHttp; }
catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");return xmlHttp; }
catch (e) { alert("Your browser does not support AJAX!");return false; }
}}}
function ajaxWrite()
{
var ajax = new ajaxFunction();
var comment = document.getElementById("comentario").value;
document.getElementById("comentario").value="";
ajax.open("POST","?Write=yes",true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("comment="+comment);
ajaxLasId();
document.getElementById("comentario").focus();
}
function ajaxRead()
{
var ajax = new ajaxFunction();
var chat = document.getElementById('chat');
chat.innerHTML='loading...<img src="img/loading.gif" />';
ajax.onreadystatechange=function()
{
if(ajax.readyState==4)
{
chat.innerHTML=ajax.responseText;
chat.scrollTop=1; // fix IE
chat.scrollTop=chat.scrollHeight;
}
}
ajax.open("GET","?Read=yes",true);
ajax.send(null);
}
function ajaxReadLast(id)
{
var ajax = new ajaxFunction();
var chat = document.getElementById('chat');
ajax.onreadystatechange=function()
{
if(ajax.readyState==4)
{
var ele=document.createElement('div');
ele.id='capa'+id;
chat.appendChild(ele);
ele.innerHTML=ajax.responseText;
$("#capa"+id).animate({ color: "#ffffff", backgroundColor: "#000000"}, "slow");
$("#capa"+id).animate({ color: "#000000", backgroundColor: "#f0f0f0"}, "slow");
chat.scrollTop=1; // fix IE
chat.scrollTop=chat.scrollHeight;
}
}
ajax.open("GET","?ReadLast=yes&id="+id,true);
ajax.send(null);
}
function ajaxLasId()
{
var chat=document.getElementById('chat');
var span=chat.getElementsByTagName('span');
for (var i = 0; i < span.length; i++)
{
var id=span[i].id;
}
var ajax = new ajaxFunction();
ajax.onreadystatechange=function()
{
if(ajax.readyState==4)
{
if(id!=ajax.responseText)
{
ajaxReadLast(id);
}
}
}
ajax.open("GET","?MaxId=yes&id="+id,true);
ajax.send(null);
}
Librerias externas:
jquery:
http://zital.no-ip.org/txat/js/jquery.js
su plugin color:
http://zital.no-ip.org/txat/js/color.js
shortcut:
http://zital.no-ip.org/txat/js/shortcut.js
y aqui el plugin de shortcut para jquery:
http://code.google.com/p/js-hotkeys/ por si alguien lo quiere implementar todo con jquery, en este caso no esta hecho por si alguien no lo quiere utilizar ;)