PHP timestamp, the variables have the same value at the end

0

The idea is to calculate the seconds that have passed since you entered the page until the button was clicked, using PHP.

The thing is, I want to do this process on the same page, I had previously tried sending the request to a separate page, in plan, the button on a page, and the request that made that button with its respective form , (that is, the action) in another. Unix time passed through a session and subtracted from the current one, in this way I knew the time that had passed.

The problem is that when doing it on the same page, when you click on the button the variables take the same value. And the result is always 0.

Example:

<?php
    $time_ = new DateTime();

    $c = $time_->getTimestamp();
    echo $c;

          if(isset($_POST['Palabras']) && strlen($_POST['Palabras'])>0 &&
          isset($_POST['Ordenadas']) && strlen($_POST['Ordenadas'])>0){


            $t = $time_->getTimestamp();
            echo $c - $t;

          }

?>

When starting page C always take X value, but when you click on button C and T take the last value obtained.

Any solution?

    
asked by Omar 08.05.2018 в 09:47
source

3 answers

2

Unless I'm wrong ... php runs on the server side, so every time you run it, all the content is executed by reloading the page.

What you want to do, I would do it with a call by AJAX to another php file that only returns the time in unix format, collect it with JS and do the calculation and show it on the screen. This will not "duplicate" the values of the variables

JS Code

  $.ajax({
    type: 'POST',
    url: 'returnTime.php',

    success: function(horaActual) {
      //ahora tienes en la variable 'horaActual' el valor unix del momento actual
      //por tanto puedes reconvertirlo a formato que necesites(ddmmyy por ejemplo) y pintarlo en un div
      var diferencia = horaActual - laHoraQueYaTenias
      $('#tuDiv').html("Han pasado " + diferencia + " segundos");
    },
    error: function(respuesta) {
      $('#tuDiv').html("Hay errores. Esto es lo que devuelve php: " + respuesta);
    }
  })

PHP code (returnTime.php)

echo time();
//todo lo que "pintes" con php en este archivo, irá a parar **tal cual** a la variable horaActual de JS, de modo que si pusieras "hola, son las ".time(), o que recibiría horaActual es, literalmente "hola, son las 32487623478263423"
    
answered by 08.05.2018 в 09:52
1

You would have to pass the initial time to the form so to the second round you have to compare

<?php
$time_ = new DateTime();

$c = $time_->getTimestamp();
echo $c;

      if(isset($_POST['Palabras']) && strlen($_POST['Palabras'])>0 &&
      isset($_POST['Ordenadas']) && strlen($_POST['Ordenadas'])>0){

  $c = isset($_POST['t_inicial'])?$_POST['t_inicial']:$c;


        $t = $time_->getTimestamp();
        echo $c - $t;

      }

?>
<form action="">
  <input type="hidden" name="t_inicial" value="<?php echo $c; ?>" />
    
answered by 08.05.2018 в 10:16
1

I really do not see any sense in wanting to do that on the server side , with PHP.

If you want to calculate the time between the start of navigation on the page and the click of a button, it would be normal to do it on the client side , using Javascript.

The procedure would be as follows:

  • Use DOMContentLoaded to capture the moment in which the page was loaded ( loadDate ), that is, the moment in which we can say with all property that the navigation started.
  • Add a listener to your button, so that when you click on it, invoke a function within the context of the DOM ( mostrarCalculo ). This function will obtain a variable with the exact moment when the button was pressed ( clickDate ) and calculate the difference in seconds between that moment and the variable loadDate obtained at the moment of loading the page.
  • Here's an example:

    document.addEventListener("DOMContentLoaded", function(event) {
      var loadDate = new Date();
      var btn = document.getElementById("btnCalcular");
      btn.onclick = mostrarCalculo;
    
      function mostrarCalculo() {
        var clickDate = new Date();
        var difSeconds = (clickDate.getTime() - loadDate.getTime()) / 1000;
        console.log("Han pasado " + difSeconds + " segundos entre el inicio de la página y el click del botón");
      }
    });
    <button id="btnCalcular">Mostrar Cálculo</button>

    I hope you find it useful.

        
    answered by 08.05.2018 в 10:40