How can a javascript code update the server’s direct time?

Asked

Viewed 705 times

1

I’m using a javascript code that uploads the talker’s photo(a) according to the date and time it’s in the air. I would like the code to exchange the images according to the time of MY SERVER and not of the user’s computer, so that the photos are also displayed correctly in another time zone. How should I proceed? Follow the code below:

<!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>Untitled Document</title>
<script>

    function rodarImagens(){
            var current = new Date();
            var agora = current.getDay();
            var hora = current.getHours();
            var minutos = current.getMinutes();

            var locutor = document.getElementById('locutor');
switch (agora){
                    case 0: //domingo
                            if(hora >= 0 && hora < 6){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 6 && hora < 9){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 9 && hora < 12){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 12 && hora < 13){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 13 && hora < 17){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 17 && hora < 18){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 18 && hora < 24){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                    break
                    case 1: //segunda
                            if(hora >= 0 && hora < 7){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 7 && hora < 9){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 9 && hora < 12){ locutor.src = 
"/site103fm/imagenshorario/locutor1.png"}
                            if(hora >= 12 && hora < 14){ locutor.src = 
"/site103fm/imagenshorario/locutor2.png"}
                            if(hora >= 14 && hora < 16){ locutor.src = 
"/site103fm/imagenshorario/locutor3.png"}
                            if (hora == 16 && minutos < 40){locutor.src = 
"/site103fm/imagenshorario/locutor3.png"}
                            if (hora == 16 && minutos >= 40){locutor.src = 
"/site103fm/imagenshorario/locutor4.png"}
                            if(hora >= 17 && hora < 19){ locutor.src = 
"/site103fm/imagenshorario/locutor4.png"} 
                            if(hora >= 19 && hora < 24){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                    break
                    case 2: //terça

                    break        
                    case 3: //quarta

                    break
                    case 4: //quinta

                    break
                    case 5: //sexta

                    break                   
                    case 6: //sábado
                            if(hora >= 0 && hora < 8){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 8 && hora < 10){ locutor.src = 
"/site103fm/imagenshorario/operador .png"}
                            if(hora >= 10 && hora < 12){ locutor.src = 
"/site103fm/imagenshorario/locutor1.png"}
                            if(hora >= 12 && hora < 13){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                            if(hora >= 13 && hora < 17){ locutor.src = 
"/site103fm/imagenshorario/locutor5.png"}
                            if(hora >= 17 && hora < 19){ locutor.src = 
"/site103fm/imagenshorario/locutor3.png"}
                            if(hora >= 19 && hora < 24){ locutor.src = 
"/site103fm/imagenshorario/operador.png"}
                    break   
            }
            setTimeout(function(){ rodarImagens() }, 1000);
    }
    </script>
</head>

<body onload="rodarImagens()">
<img src="" id="locutor" style="right:6px;margin-top:7px;position: absolute; 
z-index: 99999999;" />
</body>
</html>
  • Javascript is a language that runs directly in the user’s browser, so you would have to pull this date from somewhere as an API or have that date saved on your page so that the script can pull it. Maybe I am wrong and this library can help you: https://github.com/NodeGuy/ServerDate

  • What language is used on the site?

  • I am using Joomla. PHP with Mysql database.

  • I recommend studying Ajax and implementing on your site. If you have any questions, ask here that we would be happy to help.

  • Make a move on this topic, which is difficult to analyze the code. ;)

2 answers

0

The fact is that pulling in real time without reloading the page can lock the Script if the server in question falls, so I’ll show you how to order the date and time by PHP with AJAX and without the problem of CACHE and if the server comes to fall it will use the will not try to pull the time of the server and yes of the browser preventing the function to stop running Javascript.

Let’s create a file PHP that always manages the time in the same format as the new Date() of Javascript: Realtime.php

<?php
echo  "realtime = new Date('".date("Y-m-d\TH:i:s")."');";
?>

Now you will create this function called Realtime above the rodarImagens:

/* Iniciar variavel com tempo caso o servidor caia */
var realtime = new Date();

function clockServer(){
    nocache = nocache.getFullYear()+""+nocache.getMonth()+""+nocache.getDay()+nocache.getHours()+nocache.getMinutes()+nocache.getSeconds();

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            /*Requistar e executar resultado do JS dinâmico*/
            eval(xhttp.responseText);
        }
        if (this.readyState == 4 && this.status == 404) {
            /*Caso o servidor caia*/
            realtime = new Date();
        }
    };
    xhttp.open("GET", "realtime.php?"+nocache, true);
    xhttp.send();
}

In function rodaImagens change the first variable to copy a global variable that we will call you realttime (real time):

function rodarImagens(){
    var current = realtime;
    var agora = current.getDay();
    var hora = current.getHours();
    var minutos = current.getMinutes();

At the end of that same function replace by that:

setTimeout(function(){ clockServer() }, 1200);

In the HTML BODY code replace the onload call with this:

<body onload="clockServer()">

But in any case I advise to take the complete modified code:

<!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>Untitled Document</title>
<script>
<!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>Untitled Document</title>
<script>
/* Iniciar variavel com tempo caso o servidor caia */
var realtime = new Date();

function clockServer(){
	var nocache = new Date();
	nocache = nocache.getFullYear()+""+nocache.getMonth()+""+nocache.getDay()+nocache.getHours()+nocache.getMinutes()+nocache.getSeconds();

	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
			/*Requistar e executar resultado do JS dinâmico*/
			eval(xhttp.responseText);
		}
		if (this.readyState == 4 && this.status == 404) {
			/*Caso o servidor caia*/
			realtime = new Date();
		}
		rodarImagens();
	};
	xhttp.open("GET", "realtime.php?"+nocache, true);
	xhttp.send();
}

function rodarImagens(){
	var current = realtime;
	var agora = current.getDay();
	var hora = current.getHours();
	var minutos = current.getMinutes();
	console.log(realtime);
    
	var locutor = document.getElementById('locutor');
	switch (agora){
		case 0: //domingo
			if(hora >= 0 && hora < 6){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 6 && hora < 9){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 9 && hora < 12){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 12 && hora < 13){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 13 && hora < 17){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 17 && hora < 18){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 18 && hora < 24){ locutor.src = "/site103fm/imagenshorario/operador.png"}
		break
		case 1: //segunda
			if(hora >= 0 && hora < 7){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 7 && hora < 9){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 9 && hora < 12){ locutor.src = "/site103fm/imagenshorario/locutor1.png"}
			if(hora >= 12 && hora < 14){ locutor.src = "/site103fm/imagenshorario/locutor2.png"}
			if(hora >= 14 && hora < 16){ locutor.src = "/site103fm/imagenshorario/locutor3.png"}
			if (hora == 16 && minutos < 40){locutor.src = "/site103fm/imagenshorario/locutor3.png"}
			if (hora == 16 && minutos >= 40){locutor.src ="/site103fm/imagenshorario/locutor4.png"}
			if(hora >= 17 && hora < 19){ locutor.src = "/site103fm/imagenshorario/locutor4.png"} 
			if(hora >= 19 && hora < 24){ locutor.src = "/site103fm/imagenshorario/operador.png"}
		break
		case 2: //terça

		break        
		case 3: //quarta

		break
		case 4: //quinta

		break
		case 5: //sexta

		break                   
		case 6: //sábado
			if(hora >= 0 && hora < 8){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 8 && hora < 10){ locutor.src = "/site103fm/imagenshorario/operador .png"}
			if(hora >= 10 && hora < 12){ locutor.src = "/site103fm/imagenshorario/locutor1.png"}
			if(hora >= 12 && hora < 13){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 13 && hora < 17){ locutor.src = "/site103fm/imagenshorario/locutor5.png"}
			if(hora >= 17 && hora < 19){ locutor.src = "/site103fm/imagenshorario/locutor3.png"}
			if(hora >= 19 && hora < 24){ locutor.src = "/site103fm/imagenshorario/operador.png"}
		break
	}
	setTimeout(function(){ clockServer() }, 5000);
}
    </script>
</head>

<body onload="clockServer()">
<img src="" id="locutor" style="right:6px;margin-top:7px;position: absolute; 
z-index: 99999999;" />
</body>
</html>
		case 2: //terça

		break        
		case 3: //quarta

		break
		case 4: //quinta

		break
		case 5: //sexta

		break                   
		case 6: //sábado
			if(hora >= 0 && hora < 8){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 8 && hora < 10){ locutor.src = "/site103fm/imagenshorario/operador .png"}
			if(hora >= 10 && hora < 12){ locutor.src = "/site103fm/imagenshorario/locutor1.png"}
			if(hora >= 12 && hora < 13){ locutor.src = "/site103fm/imagenshorario/operador.png"}
			if(hora >= 13 && hora < 17){ locutor.src = "/site103fm/imagenshorario/locutor5.png"}
			if(hora >= 17 && hora < 19){ locutor.src = "/site103fm/imagenshorario/locutor3.png"}
			if(hora >= 19 && hora < 24){ locutor.src = "/site103fm/imagenshorario/operador.png"}
		break
	}
	setTimeout(function(){ realTime() }, 1000);
}
    </script>
</head>

<body onload="realTime()">
<img src="" id="locutor" style="right:6px;margin-top:7px;position: absolute; 
z-index: 99999999;" />
</body>
</html>

Look, if this method does not work I send the files ready for you, because the code is big and it is easy to get lost.

  • 1

    404 is not found error in HTTP, the ideal would be to check if it is different from the range of 200 and 299 in Ajax, for example if (this.readyState == 4) { return; } /*se não tiver concluido ainda */&#xA;&#xA;if (this.status >= 200 || this.status < 300) {&#xA; eval(xhttp.responseText);&#xA;} else {&#xA; realtime = new Date();&#xA;} ... another suggestion is not to use eval, simply take the result of the HTTP request like this <?php echo date("Y-m-d\TH:i:s"); (the ?> is dispensable/optional in PHP scripts) and in Ajax do this:

  • 1

    if (this.readyState == 4) { return; } /*se não tiver concluido ainda */&#xA;&#xA;if (this.status >= 200 || this.status < 300) {&#xA; realtime = new Date(xhttp.responseText);&#xA;} else {&#xA; realtime = new Date();&#xA;}

0

You can make php itself return the image and apply the whole logic to it. I’ll leave below an example of how it could be done.

File that makes the image available

<img src="#" alt="imagem locutor" id="locutor" />
<script>
    var intervaloAtualizaImagem = 60;
    function checarImagem() {
        var locutor = document.getElementById('locutor');
        locutor.src = 'carrega-imagem.php?hash=' + new Date().getTime();
        setTimeout(checarImagem, intervaloAtualizaImagem * 1000);
    }
    checarImagem();
    setTimeout(checarImagem, intervaloAtualizaImagem * 1000);
</script>

Script php upload.

<?php

// Representação numérica ISO-8601 do dia da semana (adicionado no PHP 5.1.0) / 1 (para Segunda) até 7 (para Domingo)
$dia = date('N');

// Representação da hora atual no formato 24-horas de uma hora com zero à esquerda
$hora = date('H');

// Minutos com zero à esquerda
$hora = date('i');

// identificando a imagem a ser exibida
switch($dia) {

    // segunda
    case 1:

        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // terça
    case 2: 
        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // quarta
    case 3: 
        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // quinta
    case 4: 
        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // sexta
    case 5: 
        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // sabado
    case 6: 
        if(hora >= 0 && hora < 8)
            $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        if(hora >= 8 && hora < 10)
            $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        if(hora >= 10 && hora < 12)
            $imagem = __DIR__ . '/site103fm/imagenshorario/locutor1.png';
        if(hora >= 12 && hora < 13)
            $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        if(hora >= 13 && hora < 17)
            $imagem = __DIR__ . '/site103fm/imagenshorario/locutor5.png';
        if(hora >= 17 && hora < 19)
            $imagem = __DIR__ . '/site103fm/imagenshorario/locutor3.png';
        if(hora >= 19 && hora < 24)
            $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
    // domingo
    case 7: 
        $imagem = __DIR__ . '/site103fm/imagenshorario/operador.png';
        break;
}

// informando tamanho do aquivo e não gerando cache
header('Expires: 0');
header('Content-Length: ' . filesize($file));
header("Content-type: image/png");

// retornando a imagem
readfile($imagem);

Observation 1: This code can be improved, if you have a database registration it can delete this switch and pick up via SQL the current operator and already display the image.

Observation 2: With I noticed that the minimum time variation is in minutes I increased the refresh time to 60 seconds (1 minute).

Observation 3: You need to check if the path of the images I put on the switch is the actual path relative to your server script.

Browser other questions tagged

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