Update the echo on a page every minute

1

I'm displaying the time in the user pane with the code:

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

Using the echo command:

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

It turns out that the displayed time only changes if I press f5. If I do not press f5 it looks like this:

Is there any way I can do this echo update every minute?

    
asked by anonymous 14.04.2016 / 00:53

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><pid="data_hora"></p>

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

    
14.04.2016 / 02:56
2

PHP does not refresh the page so you can initialize your javascript with the date of the server:

<?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 did not put the date inside the new Date (), because what works in chrome does not work firefox, in which case it will always work in both. You can improve the code to show 0, so it would look like 3:03:03 and not 3: 3: 3.

    
14.04.2016 / 05:17