Ver Mensaje Individual
  #1 (permalink)  
Antiguo 16/11/2007, 04:17
Avatar de ZiTAL
ZiTAL
 
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 2 meses
Puntos: 62
De acuerdo ZiTALK version 2 Beta litle: Ajax Chat

Hola a todos, el chat que hice (http://www.forosdelweb.com/f77/zital...x-chat-530567/) no me acababa de convencer entoces se me ocurrio implementar la idea de MaBoRaK, que solo se añadan las nuevas entradas, asi ahorramos mas ancho de banda y ademas podemos mirar los anteriores comentarios.

El anterior proyecto pasa a:

http://zital.no-ip.org/txat2/

y el nuevo:

http://zital.no-ip.org/txat/

Bueno esto tambien va con licencia LGPL:
http://www.gnu.org/licenses/lgpl.html

e aqui el codigo de la version litle, que es la mas simple y la mas facil de entender, con la plantilla incrustada en la pagina:

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("localhost","usuario","contraseña","nombre_BD");
// 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">
		setInterval("ajaxLasId()",5000);	
	</script> 
</head>	 
<body>
<div>
	<form method="post" action="" onsubmit="return ajaxWrite()">
		<p>
			<input type="text" id="comentario" size="100" maxlength="100"/>
			<input type="submit" name="submit" value="submit" />			
		</p>
	</form>
</div>
<div id="chat">
</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;    
    ajax.open("POST","?Write=yes",true);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajax.send("comment="+comment);  
    ajaxLasId();
    document.getElementById("comentario").value="";
    document.getElementById("comentario").focus();
    return false;
 }   
function ajaxRead()
 {
  var ajax = new ajaxFunction();
  var chat = document.getElementById('chat');
  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);    
 }
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.
- Ya no hay un campo oculto con el hash, se mira el id del ultimo span.
- Ahora se pueden enviar los comentarios pulsando enter, ya que se hace añade el comentario en un onsubmit, que posteriormente retorna FALSE para que no recargue la pagina.
- Añadida la libreria de animaciones jquery,+ su plugin para los colores: color.js
- Probado en: IE, Firefox, Opera, Safari y en cuanto llegue a casa pruebo en Konqueror.

si encuentro tiempo para hacer el codigo extendido, no lo hare tan flexible, ya que como he podido ver dificulta la comprension del codigo.

Espero que os guste.
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan

Última edición por ZiTAL; 20/11/2007 a las 08:57 Razón: algunos errores de codigo ;)