How to count the time the user takes on the page?

Asked

Viewed 1,862 times

1

I am making a program in PHP, Javascript and Mysql about questions and answers.

Well, in this code I need to count the time it takes the user to answer the question and store it in a variable to use the value in another code.

Also, is there any way to make the timer start by itself as soon as the page is accessed?

<html>
<head>
    <title>Responder</title>
</head>
    <body>  
        <?php
            echo"<center>";
            echo"<h1>PERGUNTA</h2>";

            $Servidor = "localhost";
            $BancoDeDados = "DESAFIO";
            $Usuario = "root";
            $Senha = "123";
            $db = mysql_connect ($Servidor,$Usuario,$Senha);
            $basedados = mysql_select_db($BancoDeDados);

            $consulta ='Select QUESTAO, ALTERNATIVACORRETA, ALTERNATIVA_A, ALTERNATIVA_B, ALTERNATIVA_C, ALTERNATIVA_D, ALTERNATIVA_E from PERGUNTA where pergunta.ID = '.$_GET["ID"].' Order by ID;';
            $resultado = mysql_query($consulta) or print (mysql_error());
            while ($linha = mysql_fetch_array($resultado))
            {
               $Questao=$linha["QUESTAO"];
               $ALTERNATIVACORRETA=$linha["ALTERNATIVACORRETA"];
               $ALTERNATIVA_A=$linha["ALTERNATIVA_A"];
               $ALTERNATIVA_B=$linha["ALTERNATIVA_B"];
               $ALTERNATIVA_C=$linha["ALTERNATIVA_C"];
               $ALTERNATIVA_D=$linha["ALTERNATIVA_D"];
               $ALTERNATIVA_E=$linha["ALTERNATIVA_E"];
            }

            $consulta2 ='Select ID from ALUNO;';
            $resultado2 = mysql_query($consulta2) or print (mysql_error());
            while ($linha2 = mysql_fetch_array($resultado2))
            {
               $ALUNO=$linha2["ID"];
            }

            echo 
            '
               <Form action="responder.php?ID='.$_GET["ID"].'&" method="POST">
                  <table border=1 align=center>
                     <font size=25 color=red>'.$Questao.'</font>  <p>

                    <tr> 
                        <td> 
                            A) <input type="radio" name="resposta" class="txt" maxlength="15" value=A>  
                               '.$ALTERNATIVA_A.' 
                        </td>
                    </tr> 
                    <tr> 
                        <td>
                            B) <input type="radio" name="resposta" class="txt" maxlength="15" value=B> 
                               '.$ALTERNATIVA_B.' 
                        </td>
                    </tr> 

                    <tr> 
                        <td> 
                            C) <input type="radio" name="resposta" class="txt" maxlength="15" value=C>
                               '.$ALTERNATIVA_C.' 
                        </td>
                    </tr> 

                    <tr> 
                        <td> 
                            D) <input type="radio" name="resposta" class="txt" maxlength="15" value=D> 
                               '.$ALTERNATIVA_D.'
                        </td>
                    </tr> 

                    <tr> 
                        <td> 
                            E) <input type="radio" name="resposta" class="txt" maxlength="15" value=E> 
                               '.$ALTERNATIVA_E.'
                        </td>
                    </tr> 


                </form>
                </table>

                <p>

                <input type="submit" value="Responder">

                    <p>   

                         <a href="INDEX.php"> <font color=red> Principal </font> <a> &bull;
                         <a href="login_aluno.php"> <font color=red> Aluno </font> <a>  

            ';

        ?>  
            <script type="text/javascript" language="JavaScript">
            var segundo = 0+"0";
            var minuto = 0+"0";
            var hora = 0+"0";

            function tempo(){   
               if (segundo < 59){
                  segundo++
                  if(segundo < 10){segundo = "0"+segundo}
               }else 
                  if(segundo == 59 && minuto < 59){
                     segundo = 0+"0";
                minuto++;
                if(minuto < 10){minuto = "0"+minuto}
                  }
               if(minuto == 59 && segundo == 59 && hora < 23){
                  segundo = 0+"0";
                  minuto = 0+"0";
                  hora++;
                  if(hora < 10){hora = "0"+hora}
               }else 
                  if(minuto == 59 && segundo == 59 && hora == 23){
                     segundo = 0+"0";
                minuto = 0+"0";
                hora = 0+"0";
                  }
               form.cronometro.value = hora +":"+ minuto +":"+ segundo
            }
            </script>

            <form name="form">
            <input type="text" name="cronometro" value="00:00:00" readonly="readonly" />
            <br />
            <button type="button" onclick="setInterval('tempo()',983);return false;">Iniciar Cronômetro</button>
            </form>

    </body>
</html>
  • Rizzo, your code is really messed up, can you tell what you’ve been trying to do? A chronometer ?

  • You want the result of the string hora +":"+ minuto +":"+ segundo in a variable, or the three variables with their isolated values?

  • I edited the question explaining better

  • 1

    Not related to your problem, but not least: Your system has only 1 student?

  • No, they’re more than one

  • 1

    So you have a problem, this consultation: $consulta2 ='Select ID from ALUNO;'; is bringing all students, and the while you do selects only the latter. Somewhere you should filter that query. Another thing, you shouldn’t use the functions mysql_* they have been deprecated, use the functions mysqli_* or the PDO

Show 1 more comment

2 answers

2

Using the jQuery can create a counter for when the page is loaded, and records the time whenever the page is updated or even closed, starting again when reopened «1».

<script>
var inicio;
$(document).ready(function(){
    inicio = new Date();
    inicio = inicio.getTime();
    $(window).unload(function(){
    fim = new Date;
    fim = fim.getTime();
    $.ajax({
    url: 'time.php',
    data: {'time': fim - inicio},
    success: function(i){$('#demo').html(i);}
    });

    });
});
</script>

You can go recording time, through settings PHP. How time is provided to us in ms just convert to s and then to a time format, so you can know exactly how many seconds, minutes or hours were spent (as) «2».

<?php
# converter o tempo para um formato legivel
function converter($tempo)
{
    $hora = 0;
    $tempo = $tempo / 1000;
    $ms = str_replace('0.', '', $tempo - floor($tempo));
    if($tempo > 3600)
    {
        $hora = floor($tempo / 3600);
    }
    $tempo = $tempo % 3600;
    $out = str_pad($hora, 2, '0', STR_PAD_LEFT) . gmdate(':i:s', $tempo) . ($ms ? ".$ms" : '');
    return $out;
}
if(isset($_GET['time'])){
    $file = fopen('time.txt', 'w');
    if($file){
        fwrite($file, converter($_GET['time']));
        fclose($file);
    }
}

?>

0

You can show the time counter in any div and then pick up the value in the click event or when to send the data to php.

Example:

var startTime;

function display() {
  var endTime = new Date();
  var timeDiff = endTime - startTime;
  timeDiff /= 1000;
  var seconds = Math.round(timeDiff % 60);
  timeDiff = Math.floor(timeDiff / 60);
  var minutes = Math.round(timeDiff % 60);
  timeDiff = Math.floor(timeDiff / 60);
  var hours = Math.round(timeDiff % 24);
  timeDiff = Math.floor(timeDiff / 24);
  $("#time").text(hours + ":" + minutes + ":" + seconds);
  setTimeout(display, 1000);
}

startTime = new Date();
setTimeout(display, 1000);

$("#button").click(function() {
  alert("Meu tempo é: " + $("#time").text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="time"></div>
<button type="button" id="button">Pega Valor</button>

It already gives a good foundation on what you can do, if you need to format the date value of a look at the Date documentation of js.

Browser other questions tagged

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