Update echo on a page every minute

Asked

Viewed 1,136 times

1

I’m displaying the time on the user panel with the code:

<?php
date_default_timezone_set('America/Sao_Paulo');
$date = date('d-m-Y H:i');
?>

Through the echo command:

<?php
  require("includes/serverTime.php");
  echo "<div class=\"date\">BR, $date</div>";

Turns out the time display only changes if I press F5. If I don’t press F5 it looks like this: inserir a descrição da imagem aqui

Is there any way I can get this echo updated every minute?

  • Maybe the best solution is to use javascript. With php, you’ll have to update every time anyway.

  • If you don’t want to use javascript (but don’t have any advantage in doing so), put that time inside an iframe and at the head of that iframe page you use a meta refresh. But the cool is with javscript itself, which then counts the seconds too, is dynamic. Much better than with php only.

2 answers

4


If you want to do with Jquery do so:

$(function() {
	 var data_hora = document.getElementById("data_hora");
	 window.setInterval(function(){
	    var now = new Date
	    data_hora.innerHTML = "BR, " + now.getDay() + "/" + now.getDate() + "/" + now.getMonth() +	"   " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
	 },5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="data_hora"></p>

I used the function setInterval which executes a function that is passed to it in the first parameter and as the second parameter the time in seconds for it to execute the function.

  • Although it is a php page, what will make the page update is not php, but this html header command you inserted, so it’s not really a solution only in php.

  • It is true @Diegof my mistake I will leave only the part with Jquery if it suits him!

2

PHP does not refresh on the page so You can initialize your javascript with the server date:

<?php
date_default_timezone_set('America/Sao_Paulo');
?>
<div class="date">BR, <span id="server_time"></span></div>
<script>
    var server_time = document.getElementById("server_time");
    var now = new Date(<?=date('Y')?>, <?=date('m')-1?>, <?=date('d')?>, <?=date('H')?>, <?=date('i')?>, <?=date('s')?>, 0);
    window.setInterval(function(){
        now.setSeconds(now.getSeconds() + 1);
        server_time.innerHTML = now.getDate() + "/" + (now.getMonth() + 1 )+ "/" + now.getFullYear() +  "   " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
    },1000);
</script>

Why I didn’t put the date inside the new Date(), because what works on Chrome doesn’t work firefox, in which case it will always work on both. You can improve the code to show 0, so it would look 03:03:03 and not 3:3:3.

  • Please help me convert the hours to show 0 by staying: 03:03:03 and not 3:3:3. I’m trying to do it with PHP but I’m not getting it. What you advise me?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.