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

1

I'm doing a PHP, JavaScript, and MySQL question and answer program.

Well, in that 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 on its own once 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>
    
asked by anonymous 03.12.2015 / 00:19

2 answers

2

Using jQuery you can create a counter for when the page loads, and it records the time every time the page is updated or even closed, and starts again when it reopens « 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 record time using PHP settings. Since time is supplied to us with ms just convert to s and then to a time format, so you can know exactly how many seconds, minutes or hours were spent en2 ».

<?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);
    }
}

?>
    
03.12.2015 / 06:58
0

You can display the time counter in any div and then get the value in the click event or at the time of sending the data to the 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><divid="time"></div>
<button type="button" id="button">Pega Valor</button>

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

    
03.12.2015 / 01:02