Update a PHP variable within a Javascript function

0

I am using the following code to display the current time of the server:

<p id="demo"></p>
<script>
  function segundoAtual() {
    var n = <?php
	date_default_timezone_set('America/Sao_Paulo');
	$cH = date('G');
	$cM = date('i');
	$cS = date('s');
	echo ($cH*60*60)+($cM*60)+$cS;
	?>;
    	var segundosInicio = inicioYujiaLynxA+(-difLynx);

c = (( n - segundosInicio + duraYujia ) % duraYujia ) / duraYujia;

i = Math.floor((mapYujia.length * 2 - 2) * c);
if( i >= mapYujia.length ) i = mapYujia.length * 2 - i - 1;

var pin = document.getElementById('pin');
pin.style.left = (mapYujia[i][0]/600*100) + '%';
pin.style.top  = (mapYujia[i][1]/757*100) + '%';
  }
    segundoAtual();
    setInterval(segundoAtual, 1);
</script>

The variables segundosInicio , inicioYujiaLynxA and difLynx are defined in another file, called by <script src="servers.js"></script> at the beginning of the document.

The variable segundoAtual defines the position of an element (pin) on a map ...

The result is obtained in seconds since midnight today.

Or is setInterval not running to update the time, or can the variable only be refreshed if the page is reloaded?

    
asked by anonymous 07.03.2017 / 02:01

1 answer

2

Only when the page is updated, would you do the following:

Create a PHP page that returns the time of the server. Create a second page with your javascript by calling via ajax that page that returns the time. So you can update your javascript element.

test.php

<script   src="https://code.jquery.com/jquery-3.1.1.min.js"integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
<p id="demo"></p>
<script>
$( document ).ready(function() {
  // Handler for .ready() called.
        update();
});
function update(){
setInterval(
    function() {

$.ajax({
    url: "hora.php",
    success: function(n){
  document.getElementById("demo").innerHTML = n;
    segundoAtual(parseInt(n))
    }
});

    },

1000);
}

    function segundoAtual(n) {

        var segundosInicio = inicioYujiaLynxA+(-difLynx);

c = (( n - segundosInicio + duraYujia ) % duraYujia ) / duraYujia;

i = Math.floor((mapYujia.length * 2 - 2) * c);
if( i >= mapYujia.length ) i = mapYujia.length * 2 - i - 1;

var pin = document.getElementById('pin');
pin.style.left = (mapYujia[i][0]/600*100) + '%';
pin.style.top  = (mapYujia[i][1]/757*100) + '%';
  }

</script>

hora.php

<?php
date_default_timezone_set('America/Sao_Paulo');
$cH = date('G');
$cM = date('i');
$cS = date('s');
echo ($cH*60*60)+($cM*60)+$cS;
?>
    
07.03.2017 / 02:06