Webmaster > PHP
Problema de Actualización de una petición PhP
shichibukai:
Buenas quisiera solucionar este problema que tengo. Necesito hacer uso de un Timer PHP. Para ello he utilizado un poco de JavaScript y de Ajax para realizar la consulta PHP al servidor de manera que constantemente se esté mostrando la hora. Mi problema es que por lo visto la consulta PHP que siempre realizo para preguntar por el tiempo siempre me da el mismo contador :S. Lo cual no se si estoy cometiendo algún error o es que en realidad no tengo permisos para realizar una petición constante para pedir la hora.
La página sería:
--- Código: ---<html>
<head>
<title><?=$_SERVER['HTTP_HOST'];?></title>
<link rel="shortcut icon" type="image/ico" href="http://www.quijost.com/favicon.ico">
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<style type="text/css">
.dir{list-style-image:url(http://quijost.com/img/dir.png);list-style-type:square;}
.file{list-style-image:url(http://quijost.com/img/file.png);list-style-type:square;}
a:link,a:visited{color:#4D5A26;text-decoration:none;}
</style>
<script type="text/javascript">
function copiar_hora()
{
var valor = document.getElementById("temporizador").value;
document.getElementById("temp_copiado").value = valor;
}
function nuevo_ajax()
{
var xmlhttp=false;
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
{
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
var seg = 0;
function timer()
{
seg++;
ajax=nuevo_ajax();
ajax.open("GET", "script_hora.php",true);
ajax.onreadystatechange=function()
{
if (ajax.readyState==4)
{
document.getElementById("temporizador").innerHTML = ajax.responseText;
document.getElementById("temp_copiado").value = seg;
}
}
ajax.send(null)
setTimeout('timer();',1000);
}
</script>
</head>
<body style="background-color:#A8D324;margin:0px;padding:0px" onLoad="setTimeout('timer();',1000);">
<div style="background:url(http://quijost.com/foro/Themes/core/images/catbg.jpg) repeat-x scroll 0 0 #B7CF6F;color:#FFFFFF;padding-left:10px;padding-right:10px;height:120px;">
<a title="quijost.com :: El hospedaje de origen manchego" href="http://www.quijost.com" style="text-decoration:none">
<img title="quijost.com :: El hospedaje de origen manchego" alt="quijost.com :: El hospedaje de origen manchego" src="http://www.quijost.com/img/logo.png" id="logo" border="0" />
<div style="margin-top: -26px; margin-left: 105px; font-size: 10px; color: #4D5A26" id="slogan">El hospedaje de origen manchego.</div>
</a>
</div>
<div id="content" style="padding:15px">
<div id="subcontent" style="font-size:12px">
<br>
<textarea id="temporizador" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
<input type=submit name=copy value=Copiar onmousedown="copiar_hora()">
<br>
<textarea id="temp_copiado" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
</div>
</div>
</body>
</html>
--- Fin del código ---
Y ahora el script PHP sería:
--- Código: ---<?
$fecha_actual = localtime(time());
echo time()- mktime(0, 0, 0, $fecha_actual[4]+1, $fecha_actual[3], 1900+$fecha_actual[5]);
?>
--- Fin del código ---
Muchas Gracias.- Shichibukai
ernestmego:
Hola y bienvenido shichibukai,
La siguiente parte de código en php, no la veo muy lógica:
--- Código: ---<?php $fecha_actual = localtime(time()); echo time()- mktime(0, 0, 0, $fecha_actual[4]+1, $fecha_actual[3], 1900+$fecha_actual[5]);?>
--- Fin del código ---
Estás capturando el tiempo actual y luego haces una resta del tiempo actual +1900 años por el localtime().
Simplemente haciendo una llamada a time() te devolverá el tiempo actual de cuando se realice la petición php.
Es decir:
--- Código: ---<?php echo time();?>
--- Fin del código ---
Para Ajax, te recomiendo la biblioteca Mootools con mejor soporte para todos los navegadores, ya que todo el código que has elaborado para Ajax, se simplificaría en unas cuantas líneas:
--- Código: ---<script>
window.addEvent('domready', function()
{
function copyHour()
{
$('temporizador').set('text', $('temp_copiado').get('text'))
}
var seg = 0
function timer()
{
seg++;
new Request({
'url' : 'script_hora.php',
onSuccess: function(response)
{
$('temporizador').set('text', response);
$('temp_copiado').set('text', seg)
},
}
)
}
setTimeout('timer()', 1000);
})
</script>
--- Fin del código ---
Tienes muchas demostraciones y ejemplos, por ejemplo de peticiones Ajax (clase Request) http://mootools.net/demos/?demo=Request
shichibukai:
Muchas gracias por responder de antemano. En cuanto a lo de utilizar la llamada time() no me sirve porque lo que quiero es obtener un contador de segundos del día (0-86399).
Luego al código que me pusiste de Mootools modificandolo un poco porque la función copyHour() es aquella a la que se acude con un click de un botón pues se me quedaría de la siguiente forma:
--- Código: --- <script>
window.addEvent('domready', function()
{
$('botonCopy').addEvent(
'click',
function()
{
$('temp_copiado').set('text', $('temporizador').get('text'));
}
);
function timer()
{
new Request({
'url' : 'script_hora.php',
onSuccess: function(response)
{
$('temporizador').set('text', response);
}
});
}
setTimeout('timer()', 1000);
});
</script>
--- Fin del código ---
Ahora en cuanto a los componentes HTML son:
--- Código: ---<div id="content" style="padding:15px">
<div id="subcontent" style="font-size:12px">
<br>
<textarea id="temporizador" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
<input id="botonCopy" type=submit name=copy value=Copiar>
<br>
<textarea id="temp_copiado" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
</div>
</div>
--- Fin del código ---
Y mi problema es que todo esto me arroja el error: TypeError: Object [Object DOMWindow] has no method 'addEvent'.
Esto creo que significa que Mootools no lo tengo vinculado a mi dominio. Me he bajado el archivo: mootools-core-1.4.5-full-compat-yc.js Pero no sabria que hacer con él, ni tampoco que líneas poner en la cabecera HTML para que se solucione este problema. Podrás intuir que soy novato en este tema :(.
Un saludo- Gracias.
shakaran:
Para cargar Mootools en tu dominio simplemente necesitas:
--- Código: ---<script src="/ruta_al_archivo/mootools-core-1.4.5-full-compat-yc.js"></script>
--- Fin del código ---
Para obtener los segundos que han transcurrido del día, time() con mktime() y date() te vale perfectamente, por ejemplo:
--- Código: ---<?php
$current_time = time();
$current_year = date('Y', $current_time);
$current_day = date('d', $current_time);
$current_month = date('n', $current_time);
$day_reset = mktime(0, 0, 0, $current_month, $current_day, $current_year);
$day_seconds = $current_time - $day_reset;
echo $day_seconds;
--- Fin del código ---
Si además quieres asegurarte la franja horaria de España, deberías utilizar:
--- Código: ---<?php
date_default_timezone_set('Europe/Madrid');
$current_time = time();
$current_year = date('Y', $current_time);
$current_day = date('d', $current_time);
$current_month = date('n', $current_time);
$day_reset = mktime(0, 0, 0, $current_month, $current_day, $current_year);
$day_seconds = $current_time - $day_reset;
echo $day_seconds;
--- Fin del código ---
También te recomiendo no escribir los ; en javascript, a menos que sea estrictamente necesario o que quieras escribir más caracteres.
shichibukai:
Okis ya no me da el error de no encontrado addEvent. Pero en realidad esto no me hace nada :S. Te pongo todo el código del script PHP para sino te importa que me digas que estoy haciendo mal :(.
--- Código: ---<html>
<head>
<title><?=$_SERVER['HTTP_HOST'];?></title>
<link rel="shortcut icon" type="image/ico" href="http://www.quijost.com/favicon.ico">
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<style type="text/css">
.dir{list-style-image:url(http://quijost.com/img/dir.png);list-style-type:square;}
.file{list-style-image:url(http://quijost.com/img/file.png);list-style-type:square;}
a:link,a:visited{color:#4D5A26;text-decoration:none;}
</style>
<script src="/public_html/mootools-core-1.4.5-full-compat-yc.js">
window.addEvent('domready', function()
{
$('botonCopy').addEvent(
'click',
function()
{
$('temp_copiado').set('text', $('temporizador').get('text'));
}
);
function timer()
{
new Request({
'url' : 'script_hora.php',
onSuccess: function(response)
{
$('temporizador').set('text', response);
}
});
}
setTimeout('timer()', 1000);
});
</script>
</head>
<body style="background-color:#A8D324;margin:0px;padding:0px" onLoad="setTimeout('timer();',1000);">
<div style="background:url(http://quijost.com/foro/Themes/core/images/catbg.jpg) repeat-x scroll 0 0 #B7CF6F;color:#FFFFFF;padding-left:10px;padding-right:10px;height:120px;">
<a title="quijost.com :: El hospedaje de origen manchego" href="http://www.quijost.com" style="text-decoration:none">
<img title="quijost.com :: El hospedaje de origen manchego" alt="quijost.com :: El hospedaje de origen manchego" src="http://www.quijost.com/img/logo.png" id="logo" border="0" />
<div style="margin-top: -26px; margin-left: 105px; font-size: 10px; color: #4D5A26" id="slogan">El hospedaje de origen manchego.</div>
</a>
</div>
<div id="content" style="padding:15px">
<div id="subcontent" style="font-size:12px">
<br>
<textarea id="temporizador" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
<input id="botonCopy" type=submit name=copy value=Copiar>
<br>
<textarea id="temp_copiado" style="cursor:default; border:transparent; background-color:transparent; font-size:18px; font-weight:bold; cursor:default; text-align:center; resize:none; height:30px; width:100px;"> 0 </textarea>
<br>
</div>
</div>
</body>
</html>
--- Fin del código ---
Un saludo- Gracias.
Navegación
[#] Página Siguiente
Ir a la versión completa