Bruce Bruce - 4 months ago 29
Ajax Question

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.

Answer

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.

Comments