Foros del Web » Programando para Internet » Javascript » Frameworks JS »

ZiTALK version 2 Beta litle: Ajax Chat

Estas en el tema de ZiTALK version 2 Beta litle: Ajax Chat en el foro de Frameworks JS en Foros del Web. 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 , ...
  #1 (permalink)  
Antiguo 16/11/2007, 04:17
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
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 ;)
  #2 (permalink)  
Antiguo 16/11/2007, 11:17
 
Fecha de Ingreso: noviembre-2007
Mensajes: 24
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: ZiTALK version 2 Beta litle: Ajax Chat

Buenas ideas y buenas soluciones
Gracias Zital y MaBoRaK....
Me quedé también enganchado con la idea de retocar solo la última entrada, pero,.. me he preocupado de explorar posibilidades, como habeis visto.



Con
data TIMESTAMP, en la tabla de MySQL
no hace falta :
$date=mktime(date("H"),date("i"),date("s"),date("m "),date("d"),date("Y"));

.. se puede enviar solo
$insert="insert into chat values(".$max.",'".$comment.")";

MySQL incorpora al campo data, la fecha del servidor sin enviarle nada.


Código PHP:
// 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.")";
  
$insert="insert into chat values(".$max.",'".$comment.")"
 
  if(
trim($_REQUEST["comment"])!=NULL)
   {
    
$insert=mysql_query($insert);
   }
  
mysql_close($link);
  exit();
 } 

Última edición por jose_sv; 16/11/2007 a las 17:52
  #3 (permalink)  
Antiguo 16/11/2007, 16:20
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Re: ZiTALK version 2 Beta litle: Ajax Chat

loading.............


Quetal si conviertes todo en una CLASE, podemos usar mis paneles.

http://maborak.com/js/maborak/samples/maborak.html

mi framework ajax o lo que haga falta jeje.... no se es una idea


connection closed.
__________________

Maborak Technologies
  #4 (permalink)  
Antiguo 16/11/2007, 17:58
 
Fecha de Ingreso: noviembre-2007
Mensajes: 24
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: ZiTALK version 2 Beta litle: Ajax Chat

Y otra cosa
al hacer el campo id PRIMARY KEY NOT NULL AUTO_INCREMENT no hace falta ingresarlo tampoco MySQL ingresa el siguiente
Código PHP:
// sending comments
if($_GET["Write"]=="yes")
 {
  
$comment=htmlentities(utf8_decode($_REQUEST["comment"]));
  
$insert="insert into chat values(".$comment.")"
  if(
trim($_REQUEST["comment"])!=NULL)
   {
    
$insert=mysql_query($insert);
   }
  
mysql_close($link);
  exit();
 } 
  #5 (permalink)  
Antiguo 18/11/2007, 00:53
 
Fecha de Ingreso: noviembre-2007
Mensajes: 24
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: ZiTALK version 2 Beta litle: Ajax Chat

Joder, MaBoRaK!!!
¡¡¡¡¡Que paneles tan bonitos!!!!!
Si lo que yo construyo es rústico al lado de eso!!
¡Enhorabuena!
  #6 (permalink)  
Antiguo 18/11/2007, 08:24
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: ZiTALK version 2 Beta litle: Ajax Chat

ya te digo!!!

bueno corregido algunos fallos, + añadidos animaciones con la libreria jquery.

Edito el primer post.
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #7 (permalink)  
Antiguo 19/11/2007, 16:06
 
Fecha de Ingreso: noviembre-2007
Mensajes: 24
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: ZiTALK version 2 Beta litle: Ajax Chat

Si que es espectacular el efecto de la librería jquery
El efecto acordeón
Abrir o cerrar imágenes
o links a divs
me han gustado.
Parece magia!!! con pocas lineas que efectos !!
http://www.anieto2k.com/2006/11/15/expandable-sidebar-menu-el-acordeon-de-jquery/
  #8 (permalink)  
Antiguo 20/11/2007, 08:50
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: ZiTALK version 2 Beta litle: Ajax Chat

añadida la funcion ajaxLasId() al ajaxWrite() para que al insertar una nueva entrada la muestre automaticamente. En estos momentos estoy implementando un loading para mostrar algo mientras carga el chat, en cuanto lo tenga modificare el primer post ;)

Se me olvido comentar que el proyecto esta en:

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

Euskerie ahuen eta bijotzan

Última edición por ZiTAL; 20/11/2007 a las 08:56
  #9 (permalink)  
Antiguo 23/11/2007, 01:01
 
Fecha de Ingreso: noviembre-2007
Mensajes: 24
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: ZiTALK version 2 Beta litle: Ajax Chat

Habeis visto lo sencillo que es axax con jquery.
Quizá se pudiera expresar el archivo de un modo mas simple
Código:
$.get("index.php",
   { Read: "yes" },
   function(respuesta){
             chat.innerHTML=respuesta;
             chat.scrollTop=1; // fix IE
             chat.scrollTop=chat.scrollHeight;  	            

   }
);
  #10 (permalink)  
Antiguo 23/11/2007, 01:04
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: ZiTALK version 2 Beta litle: Ajax Chat

si esta muy bien, pero no quiero obligar a la gente que use jquery para hacer lo de ajax, digo para el que no sabe, si quieres hacer ajax con jquery por mi perfecto ;)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #11 (permalink)  
Antiguo 28/02/2010, 15:04
 
Fecha de Ingreso: mayo-2004
Ubicación: Guadalajara, Jalisco, México
Mensajes: 724
Antigüedad: 19 años, 11 meses
Puntos: 6
Respuesta: ZiTALK version 2 Beta litle: Ajax Chat

Lejos... muy lejos...
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 20:15.