Countdown PHP + Javascript

Asked

Viewed 4,202 times

1

I have a column in the database called time, she owns an event that does the following:

UPDATE users SET time = time - 1

As default gets 1800 seconds (30 minutes) right?

Now I wish recover the time going down I tried the following:

<?php
$database = new DB;

/*Selectiono meu usuário*/
$select = $database->select($username);

/*Aqui retorno tudo*/
$fetch = $select->fetch(PDO::FETCH_ASSOC);

/*Aqui imprimo na tela o conteúdo do campo time*/
echo $fetch['time'];
?>

Now I tried to do the following, to recover, but it does not appear. I mean, it does not work.

$(document).ready(function() {
    $('.contagem').css('display', 'block');
    $('.contagem').html("<?php echo $fetch['time']?>");
});

Error in first line:

$(document).ready(function() {

I reviewed this site and nothing helped me.

Edit

Whole code

<?php
$database = new DB;

/*Selectiono meu usuário*/
$select = $database->select($username);

/*Aqui retorno tudo*/
$fetch = $select->fetch(PDO::FETCH_ASSOC);

/*Aqui imprimo na tela o conteúdo do campo time*/
echo $fetch['time'];
?>
<!DOCTYPE html>
<html>
<head>
    <title>
        Contagem
    </title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>

<span class="contagem" style="display: none;"></span>

<script type="text/javascript">
        $(document).ready(function() {
        $('.contagem').css('display', 'block');
        $('.contagem').html("<?php echo $fetch['time']?>");
    });
</script>
</body>
</html>

Note: When arriving at 0 Reload a page.

  • Is this jQuery code in the PHP file or in a separate Javascript file? It needs to be in the PHP file for the PHP code snippet to be interpreted. If you are in the JS file, PHP will never see this chunk of code, although the effect I see from this would be to display the PHP code in the element .contagem instead of the value itself. You can put your complete code and error message?

  • Dude, make an ajax request, I particularly hate this kind of approach that mixes the 2.

  • Matheus, not read() but ready()

  • If you are applying these styles as soon as the page is loaded you can do this directly in the document’s HTML without needing any script. Help your browser :)

  • @Andersoncarloswoss, is in the same file, the whole code is the same, has nothing else. of course opens and closes tags PHP and script clear-cut.

  • Good but I wanted count in real time, countdown understood?

  • If it is in real time, the easiest is to count only with Javascript, using the function setTimeOut or setInterval.

Show 2 more comments

3 answers

2

The first line error is pq Voce put the read..

$(document).ready(function() {
}

I imagine you are in the same php file, when it launches that <?php within the $('.count'), correct?

To validate the time, create a setInterval, and when you get to 0, you fire the page’s Reload.

    segundos = <?php echo $fetch['time']?>;
    setInterval(function(){
        if(segundos > 0)
          segundos = segundos - 1;
        else
          location.reload();

        $('.contagem').html(segundos);

    }, 1000/*a cada segundo, esta func vai rodar*/);
  • Uncaught ReferenceError: $ is not defined

  • https://jquery.com/download/

  • The reply of the friend up there, helped me but thanks ok +1 to you tbm

2


I got this code on this reply in the English OS. As it is not possible to interpret php in the snippet below, I put the fixed value of 180 seconds (3 minutes).

/* Código exposto em uma página php */
//var contador = '<?php echo $fetch['time']?>'; /**** Variável do PHP ****/
var contador = '180';

/* A partir daqui, pode ficar em um arquivo .js */
function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      location.reload();
    }
  }, 1000);
}

window.onload = function() {
  var count = parseInt(contador),
    display = document.querySelector('#time');
  startTimer(count, display);
};
<div>Registros terminam em <span id="time">Carregando...</span>!</div>

  • opa I will test seems to be useful.

  • Worked perfectly...

  • I’m glad it worked ;) Pro OS points in English :P

  • I realized that when getting to -1 starts an error loop on the console has a way to solve this? like the time getting to -1 in case my query in question. when it reaches -1 back to 0

  • @Matheusborjes, there in the code I put to give a Reload on the page if the counter reaches below 0. To help you, post the console error message to understand what happened.

  • see: http://prntscr.com/g3v4zf

  • 1

    In this line "display.textContent = minutes + ":" + Seconds" it tries to set the html content, what is occurring is that the "display" object does not exist, it may be removed from the HTML, in this case, make a validation if it is null and if it is not, then update the text. Document.querySelector can be changed to jQuery if desired, there is no problem. It would be $("#time") instead of Document.querySelector("#time").

  • Solved was worth.

Show 3 more comments

1

I made this change to show the second time in the act and redirect to a specific page.

<h1>Nada foi encontrado no servidor</h1>
<div id="msg"></div>
<script type="text/javascript">	
	var tempo = 100;	
  setInterval(function(){
		 if(tempo >0){
		 	 tempo = tempo-1;
		 	document.getElementById('msg').innerHTML = "Voce será redirecionado em "+tempo+" segundos";
		 	if(tempo==0){		
			window.location.href = 'login';				
	}
		 }
		},tempo);
	
</script>

var time = 100; setInterval(Function(){ if(time >0){ time = time-1; Document.getElementById('msg'). innerHTML = "You will be redirected in "+time+" seconds"; if(time==0){ window.location.href = 'login'; } } },time);

Browser other questions tagged

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