Foros del Web » Programando para Internet » Javascript »

Respuestas del formulario PHP

Estas en el tema de Respuestas del formulario PHP en el foro de Javascript en Foros del Web. Buenas, es mi primer post aquí y soy nuevo en esto ya que toda mi web la conseguí hacer sin postear (mirando posts antiguo) y ...
  #1 (permalink)  
Antiguo 21/06/2009, 04:43
 
Fecha de Ingreso: junio-2009
Mensajes: 32
Antigüedad: 14 años, 10 meses
Puntos: 0
Exclamación Respuestas del formulario PHP

Buenas, es mi primer post aquí y soy nuevo en esto ya que toda mi web la conseguí hacer sin postear (mirando posts antiguo) y con ayuda de un amigo, pero ahora he llegado a un punto en la que no me veo en otro que escribir (voy al grano):

Quiero hacer un estilo de chat pero con un formulario php, he aquí un ejemplo de como lo llevo: http:/tienesuque2.webcindario.com/chat_inicio.html

Bien, si entrais y lo probais vereis que las respuestas del chat se escriben abajo, entonces los usuarios cuando llenen la pantalla no podran leer los mensajes, me gustaria saber si hay alguna forma para que las respuestas del formulario se escriban arriba de la pagina, o para que la pagina del frame de abajo (mensajes.html) se mantenga abajo todo el rato.

El codigo que uso es el siguiente:

<?php
$mensajea=$_POST['mensaje'];
$nicka=$_POST['nick'];

$archivo=fopen('mensajes.html','a+'); //abrimos el archivo

fwrite ($archivo,'<strong>'.$nicka.' dice:</strong> '.$mensajea.'<br>
'); // escribimos un nuevo mensaje

fclose($archivo); //cerramos el archivo
?>

Muchas gracias de antemano.

Última edición por tienesuque; 21/06/2009 a las 14:52
  #2 (permalink)  
Antiguo 21/06/2009, 10:15
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Respuestas del formulario PHP

Con PHP no puedes hacerlo, tienes que usar Javascript para mover el scroll de la ventana al fondo del chat.

Saludos.
  #3 (permalink)  
Antiguo 21/06/2009, 11:20
 
Fecha de Ingreso: junio-2009
Mensajes: 32
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Respuestas del formulario PHP

¿Y como hago eso?
  #4 (permalink)  
Antiguo 21/06/2009, 11:20
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Respuestas del formulario PHP

Te muevo al foro de Javascript para que te orienten mejor.

Saludos.

Tema trasladado desde PHP
  #5 (permalink)  
Antiguo 21/06/2009, 12:24
Avatar de gioramies  
Fecha de Ingreso: febrero-2008
Ubicación: Colombia
Mensajes: 217
Antigüedad: 16 años, 2 meses
Puntos: 14
Respuesta: Respuestas del formulario PHP

Hola. He visitado el enlace que colocaste y al parecer hay un script que pasa todo el tiempo ejecutándose y me ha puesto el navegador muy lento. Creo que primero deberías solucionar ese problema. No pude enviar ningún mensaje. Puedes colocar el código para que lo analicemos y te ayudemos con eso. Saludos.
  #6 (permalink)  
Antiguo 21/06/2009, 12:54
Avatar de SPAWN3000  
Fecha de Ingreso: marzo-2008
Ubicación: Bogota
Mensajes: 858
Antigüedad: 16 años, 1 mes
Puntos: 15
Respuesta: Respuestas del formulario PHP

La lentitud se debe al POST + Sleep + check +Refresh.
Estos son muchos pasos para un chat.

Recomiendo el siguiente sistema. Creo que algunas personas habian estado solicitando un ejemplo de estos hace un tiempo. Pero no recuerdo el post.
  #7 (permalink)  
Antiguo 21/06/2009, 12:58
Avatar de SPAWN3000  
Fecha de Ingreso: marzo-2008
Ubicación: Bogota
Mensajes: 858
Antigüedad: 16 años, 1 mes
Puntos: 15
Respuesta: Respuestas del formulario PHP

backend.php
Código PHP:
<?php

$filename  
dirname(__FILE__).'/data.txt';

// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if (
$msg != '')
{
  
file_put_contents($filename,$msg);
  die();
}

// infinite loop until the data file is not modified
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif filemtime($filename);
while (
$currentmodif <= $lastmodif// check if the data file has been modified
{
  
usleep(10000); // sleep 10ms to unload the CPU
  
clearstatcache();
  
$currentmodif filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo 
json_encode($response);
flush();

?>

index.html
Código:
<!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">
  <head>
    <title>Comet demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="prototype.js"></script>
  </head>
  <body>

<div id="content">
</div>

<p>
  <form action="" method="get" onsubmit="comet.doRequest($('word').value);$('word').value='';return false;">
    <input type="text" name="word" id="word" value="" />
    <input type="submit" name="submit" value="Send" />
  </form>
</p>

<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {

  timestamp: 0,
  url: './backend.php',
  noerror: true,

  initialize: function() { },

  connect: function()
  {
    this.ajax = new Ajax.Request(this.url, {
      method: 'get',
      parameters: { 'timestamp' : this.timestamp },
      onSuccess: function(transport) {
        // handle the server response
        var response = transport.responseText.evalJSON();
        this.comet.timestamp = response['timestamp'];
        this.comet.handleResponse(response);
        this.comet.noerror = true;
      },
      onComplete: function(transport) {
        // send a new ajax request when this request is finished
        if (!this.comet.noerror)
          // if a connection problem occurs, try to reconnect each 5 seconds
          setTimeout(function(){ comet.connect() }, 5000); 
        else
          this.comet.connect();
        this.comet.noerror = false;
      }
    });
    this.ajax.comet = this;
  },

  disconnect: function()
  {
  },

  handleResponse: function(response)
  {
    $('content').innerHTML += '<div>' + response['msg'] + '</div>';
  },

  doRequest: function(request)
  {
    new Ajax.Request(this.url, {
      method: 'get',
      parameters: { 'msg' : request }
    });
  }
}
var comet = new Comet();
comet.connect();
</script>

</body>
</html>
NOTA: Se debe descargar prototype y colocarlo en el mismo directorio con todos los archivos.

Crear un archivo plano de nombre: data.txt.

Una vez ejecuta la pagina, editar el archivo data.txt y notar que la pagina se actualiza por si sola.

Técnica: BOSH...usada por facebook.
  #8 (permalink)  
Antiguo 21/06/2009, 14:45
 
Fecha de Ingreso: junio-2009
Mensajes: 32
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Respuestas del formulario PHP

Buenas, la lentitud se debía a alguien que ha entrado y ha petado el chat con mil mensajes . Voy a probar ahora mismo el code que hay arriba asique lo pruebo y os digo, muchas gracias a todos.
  #9 (permalink)  
Antiguo 21/06/2009, 14:58
 
Fecha de Ingreso: junio-2009
Mensajes: 32
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Respuestas del formulario PHP

Uhm, el codigo es demasiado complicado para mí, no lo entiendo. =S
He vuelto a subir el chat en:
http:/tienesuque2.webcindario.com/chat_inicio.html
  #10 (permalink)  
Antiguo 23/06/2009, 03:01
 
Fecha de Ingreso: junio-2009
Mensajes: 32
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Respuestas del formulario PHP

Ya tengo la solución! La encontré en otro post, ha sido poner este código javascript, gracias de todas formas a todos!

Código C&#243:
Ver original
  1. <script type="text/javascript">
  2. function bajarScroll()
  3. {
  4. mensajes.scrollTo(0,10000);
  5. }
  6. </script>
  7. <body>
  8. <iframe onload="bajarScroll()" name="mensajes" title="mensajes" id="mensajes" style="position: absolute; top: 200px; left: 0px" frameBorder="NO" width="620px" height="300px" src="chat/mensajes.php"></iframe>
</body>
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.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:01.