Bruce
Bruce

Reputation: 1071

ajax php jquery realtime saving of counter

Currently the script.php works perfectly but what I want to happen, is instead of displaying the hours, minutes and seconds I want to have the 3 values combined and POSTED to log.php as $_POST['timeSpent'] as well as the value $id sent as $_POST['id'] every 1 second.

script.php

<p><span id="hours"></span>:<span id="minutes"></span>:<span id="seconds"></span></p>
<script>
  var sec = -1;
  function pad(val) { return val > 9 ? val : "0" + val; }
  setInterval(function () {
    $("#seconds").html(pad(++sec % 60));
    $("#minutes").html(pad(parseInt(sec / 60, 10) % 60));
    $("#hours").html(pad(parseInt(sec / 3600, 10)));
  }, 1000);
</script>

log.php

<?php
    include 'includes/config.php';

    $loggeduser = $_SESSION['username'];
    $stmt = "UPDATE rotator_tracking SET time_spent=:time_spent WHERE id=:id";
    $stmt = $db->prepare($stmt);
    $stmt ->execute(array(
        ":time_spent" => $_POST['timeSpent'],
        ":id" => $_POST['id']
    ));
?>

I know the variables need to be handed to ajax which hands them to the log.php but in this instance, I have no idea how to do that nor how to save it every 1 second.

Help? Perhaps example code.

Upvotes: 1

Views: 194

Answers (1)

Nicolas Racine
Nicolas Racine

Reputation: 1061

in your setInterval loop just add

$.post(
  'log.php',
  {
    timeSpent:theTimeCombinedVariable,
    id:IdVariable
  }
).done(function() {
  alert('done');
});

I did not test the code. but this is pretty much it.

Upvotes: 2

Related Questions