I'm using this jquery timer to collect time spent while it is running.
https://github.com/walmik/timer.jquery http://jquerytimer.com/
In a prior Stack Overflow post we were able to Post to another page the current accumulated time using jQuery Ajax (jQuery.timer how to get current value in php?). Many thinks to @Dakis
It seems our current solution is trying to save on any Stop and Restart of the Timer. It only needs to do a Save to DB routine IF the “Save Time and Notes” button is selected.
I’ve been researching jQuery Ajax and understand that a key/value pair is needed to be sent to the server/receiving page. I understand the first value identifies the target from which to get the "key", but I could not get a clear understanding of proper formatting for the second “value”. 'task': $('.ta_tasks').data('task’) does not seem to be passing the value as expected.
I’ve added a TextArea with an ID of “ta_tasks” and appended the current working AJAX with:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task’)
On the receiving page I added a simple alert to see if the value is being received but it is not. If I can figure out how to properly send the contents of the TextArea I could also figure out how to submit a value from the “Save Time and Notes” button so that a Pause and Restart will not also submit to the database.
Working page: http://sgdesign.com/timer2.php
Parent page script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var hasTimer = false;
/**
* Save the current timer value.
*
* Performs an ajax request to the server, which will
* save the timer value in a database table and return
* a corresponding message.
*/
function saveTime() {
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task')
},
success: function (response, textStatus, jqXHR) {
displayAlert('success', response);
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* If the status code of the response is the custom one
* defined by me, the developer, in saveTime.php, then I
* can display the corresponding error message. Otherwise,
* the displayed message will be a general user-friendly
* one - so, that no system-related infos will be shown.
*/
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayAlert('danger', message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
}
/**
* Display a bootstrap alert.
*
* @param type string success|info|warning|danger.
* @param message string Alert message.
* @return void
*/
function displayAlert(type, message) {
var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
+ '<span aria-hidden="true">×</span>'
+ '</button>'
+ '<span>' + message + '</span>'
+ '</div>';
$('.messages').html(alert);
}
// Init timer start
$('.save-timer-btn').on('click', function () {
saveTime();
});
// Init timer start
$('.start-timer-btn').on('click', function () {
hasTimer = true;
$('.timer').timer({
editable: true
});
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer resume
$('.resume-timer-btn').on('click', function () {
$('.timer').timer('resume');
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer pause
$('.pause-timer-btn').on('click', function () {
$('.timer').timer('pause');
$(this).addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
saveTime();
});
// Remove timer. Leaves the display intact.
$('.remove-timer-btn').on('click', function () {
hasTimer = false;
$('.timer').timer('remove');
$(this).addClass('d-none');
$('.start-timer-btn').removeClass('d-none');
$('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
});
// Additional focus event for this demo
$('.timer').on('focus', function () {
if (hasTimer) {
$('.pause-timer-btn').addClass('d-none');
$('.resume-timer-btn').removeClass('hidden');
}
});
// Additional blur event for this demo
$('.timer').on('blur', function () {
if (hasTimer) {
$('.pause-timer-btn').removeClass('d-none');
$('.resume-timer-btn').addClass('d-none');
}
});
});
</script>
Target Page contents:
<?php
// Price per hour variable
$cost = 50;
# require 'connection.php';
// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
/*
* This response header triggers the ajax error because the status
* code begins with 4xx (which corresponds to the client errors).
* I defined 420 as the custom status code. You can choose whatever
* code between 401 and 499 which is not officially assigned, e.g.
* which is marked as "Unassigned" in the official HTTP Status Code Registry.
* See the link.
*
* @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 420 No time value defined. Did you start the timer?');
exit();
}
// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
exit();
}
// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */
$task = $_POST['ta_tasks'];
$r = $cost / 3600 * $time;
$rate = round($r, 2);
/*
* Save the timer value in a db table using PDO library.
*/
/* $sql = 'INSERT INTO my_timer_table (
time
) VALUES (
:time
)';
$statement = $connection->prepare($sql);
$statement->execute([
':time' => $time,
]);
// Print success message.
echo 'Time (' . $time . ' seconds) successfully saved when timer was ' . $state . '.';
exit(); */
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
var a = "<?php echo $task; ?>";
alert ('task: ' + a);
</script>
</head>
<body>
<?php function secondsToTime($seconds) {
$dtF = new \DateTime('@0');
$dtT = new \DateTime("@$seconds");
return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds');
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
?>
<?php echo secondsToTime($time);
echo '<br>';
echo 'Tasks: '.$task .'<br>';
echo 'Cost: $'. $rate;
?>
</body>
</html>
Goal Summary Proper formatting of data in: 'task': $('.ta_tasks').data('task’) Understanding of Why so as to learn how to also transfer when the 'Save Time and Notes" button to invoke saving Cost and Notes to DB