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

Actualizar un div

Estas en el tema de Actualizar un div en el foro de Frameworks JS en Foros del Web. Buenas a todos; Hay alguna manera de actualizar un div si un campo se inserta en la BB.DD sin tener que refrescar toda la pagina? ...
  #1 (permalink)  
Antiguo 28/01/2010, 11:45
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Actualizar un div

Buenas a todos;
Hay alguna manera de actualizar un div si un campo se inserta en la BB.DD sin tener que refrescar toda la pagina?
Un saludo
  #2 (permalink)  
Antiguo 28/01/2010, 14:46
 
Fecha de Ingreso: enero-2010
Mensajes: 39
Antigüedad: 14 años, 3 meses
Puntos: 1
Respuesta: Actualizar un div

Se me ocurre que podria ser algo asi:

Código Javascript:
Ver original
  1. function actualiza()
  2. {
  3.     ajax=nuevoAjax();
  4.     ajax.open("GET", "ajax_inserta_db.php?var1="+var1+"var2="+var2); // En ajax_inserta_db se debe hacer el INSERT en la BD, obviamente se debe pasar con las variables a insertar
  5.  
  6.     ajax.onreadystatechange=function()
  7.     {
  8.         if (ajax.readyState==4)
  9.         {
  10.             document.getElementById("contenedor_datos").innerHTML = ajax.responseText;
  11.         }
  12.     }
  13.     ajax.send(null)
  14. }

Código HTML:
Ver original
  1. <div name="contenedor_datos" id="contenedor_datos"></div>
  2.  
  3. <input type="button" onclick="actualiza()" value="insertar">
  #3 (permalink)  
Antiguo 29/01/2010, 03:25
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Respuesta: Actualizar un div

Lo que quiero es que se actualice automaticamente, seguramente no me he explicado bien.
Supongamos que estoy leyendo una pagina y un usuario inserta un comentario. Pues el usuario que esta leyendo la pagina, no leera ese comnetario hasta que refresque la pagina. Y lo que me gustaria es que se actualizara cada vez que en esa tabla se insertaran comentarios.
Un saludo y gracias por la ayuda
  #4 (permalink)  
Antiguo 29/01/2010, 07:01
 
Fecha de Ingreso: enero-2010
Mensajes: 39
Antigüedad: 14 años, 3 meses
Puntos: 1
Respuesta: Actualizar un div

Ah dale, utilizare el mismo script anterior

Código Javascript:
Ver original
  1. <script type="text/javascript">
  2. var tmp="";
  3.  
  4. setInterval(function actualiza()
  5. {
  6.     ajax=nuevoAjax();
  7.     ajax.open("GET", "ajax_select_db.php?var1="+var1+"var2="+var2); // En ajax_select_db debes hacer el SELECT al query
  8.  
  9.     ajax.onreadystatechange=function()
  10.     {
  11.         if (ajax.readyState==4)
  12.         {
  13.             // Si el valor devuelto por AJAX no es el mismo que tenemos en TMP entonces lo muestra, si no, almacena el contenido en TMP para una siguiente revision cada X tiempo (X lo define el Setinterval... no disminuyas mucho el tiempo para no saturar la BD.
  14.             if(!(ajax.responseText==$tmp)
  15.             {
  16.                  document.getElementById("contenedor_datos").innerHTML = ajax.responseText;
  17.             } else {
  18.                  $tmp=ajax.responseText;
  19.         }
  20.     }
  21.     ajax.send(null)
  22. ,10000);
  23. </script>

Suerte
  #5 (permalink)  
Antiguo 30/01/2010, 05:58
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Respuesta: Actualizar un div

Buenas; he probado tu scrpit y me queda así
Código PHP:
<script type="text/javascript">
var 
tmp="";
 
setInterval(function actualiza()
{
    
ajax=nuevoAjax();
    
ajax.open("GET""consulta_comentario.php?var1="+var1+"var2="+var2); // En ajax_select_db debes hacer el SELECT al query
 
    
ajax.onreadystatechange=function() 
    {
        if (
ajax.readyState==4
        {
            
// Si el valor devuelto por AJAX no es el mismo que tenemos en TMP entonces lo muestra, si no, almacena el contenido en TMP para una siguiente revision cada X tiempo (X lo define el Setinterval... no disminuyas mucho el tiempo para no saturar la BD.
            
if(!(ajax.responseText==$tmp)
            {
                 
document.getElementById("mainContent").innerHTML ajax.responseText;
            } else {
                 
$tmp=ajax.responseText;
        }
    }
    
ajax.send(null)
,
1000);
</script> 
Luego he creado la pagina "consulta_comantario" y este es el codigo
Código PHP:
<?php require_once('../../Connections/deume.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$colname_comentarios "-1";
if (isset(
$_GET['var1'])) {
  
$colname_comentarios $_GET['var1'];
}
mysql_select_db($database_deume$deume);
$query_comentarios sprintf("SELECT id_comentarios FROM comentarios WHERE id_comentarios = %s ORDER BY id_comentarios DESC"GetSQLValueString($colname_comentarios"int"));
$comentarios mysql_query($query_comentarios$deume) or die(mysql_error());
$row_comentarios mysql_fetch_assoc($comentarios);
$totalRows_comentarios mysql_num_rows($comentarios);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin título</title>
</head>

<body>
<?php echo $row_comentarios['id_comentarios']; ?>
</body>
</html>
<?php
mysql_free_result
($comentarios);
?>
Pero no me actualiza el DIV "mainContent".
Pero tengo una duda... En la pagina "consulta_comentario" le he puesto que filtre por URL la variable "var1" lo que no se si esta bien echo así.
Un saludo

Última edición por visona; 30/01/2010 a las 06:18

Etiquetas: ajax
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 01:33.