How can I get the time spent on website and save that data to database using ajax call. I have tried something like below but it is not working as expected.
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$url=file_get_contents("http://ip-api.com/json/$ip");
//Convert the json to php associative array
$data = json_decode($url, true);
?>
<html>
<head>
<title>My website</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var startTime = new Date();
alert(startTime);
window.onbeforeunload = function(ajaxFunc)
{
var ajaxFunc = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var time = timeSpentMilliseconds / 1000 / 60;
$.ajax({
type: 'GET',
url: 'http://example.com/get_time/index.php',
data: 'time=' + timeSpentMilliseconds + '&t=' + time
});
};
});
</script>
</body>
</html>
The quick and dirty method
We will use the server polling every N seconds to manually calculate time user spent on the website. In order to prevent accumulating errors I'll add threshold of M seconds (M > N).
What I've did is set up a database table like this:
+--------------+------------+-------------+
| ip | total_time | last_update |
+--------------+------------+-------------+
| 12.214.43.41 | 581 | 1456534430 |
+--------------+------------+-------------+
| 41.61.13.74 | 105 | 1456538910 |
+--------------+------------+-------------+
| 112.31.14.11 | 4105 | 1456241333 |
+--------------+------------+-------------+
Then, you have a server-side script that does the next:
server.php
<?php
$servername = 'localhost';
$dbname = 'cooldb';
$username = 'dbuser';
$password = 'changeit';
$table = 'timers';
// Session timeout - threshold that user have left the site.
$session_timeout = 60;
$ip = $_GET['REMOTE_ADDR'];
$now = time();
$total_time = 0;
$last_update = time();
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Check if we have ip on our table
$stmt = $db->prepare("SELECT * FROM {$table} WHERE ip=?");
$stmt->execute([$ip]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($rows)) {
$client = reset($rows);
$total_time = $client['total_time'];
$last_update = $client['last_update'];
// Updating $total_time only when user is logged in and sending requests in $session_timeout timespan.
if ($last_update + $session_timeout > $now) {
$total_time += $now - $last_update;
}
$last_update = $now;
// Client is already recorded - update the timers.
$stmt = $db->prepare("UPDATE {$table} SET total_time=?, last_update=? WHERE ip=?");
$stmt->execute([$ip, $total_time, $last_update]);
} else {
// Client have logged in first time - create a record in db.
$stmt = $db->prepare("INSERT INTO {$table} (`ip`, `total_time`, `last_update`) VALUES ('?', '?', '?')");
$stmt->execute([$ip, $total_time, $last_update]);
}
} catch (PDOException $e) {
echo $e->getMessage();
}
$db = null;
Then, on client-side you are just making requests like this to record user activity:
// Something reasonable, below $session_timeout threshold.
var repeat = 20000;
setInterval(function(){ $.get('/server.php', function(){}); }, repeat);
I didn't tested it yet myself, but I hope you'll get the idea.
Related
I am fetching data from a psql table and passing it to javascript as json array for display as a time series chart. The data passed needs to be in the from of an array.
As the data in the table is updated periodically, I need to constantly fetch the data from psql e.g. every 15 minutes and pass updated array to javascript.
I search but so far I couldn't any solution. My question is how can I fetch data from psql periodically.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Device_Data;
var time, batt;
var timeArray = [];
var battArray = [];
var N = 12;
for (i = 0; i < N; i++) {
timeArray.push(0);
battArray.push(0); }
function dspChrt(Device_Data) {
console.log(Device_Data[0].date_time);
console.log(Device_Data[1].battery_voltage_mv);
time = Device_Data[0].date_time;
batt = Device_Data[1].battery_voltage_mv;
timeArray.shift();
timeArray.push(time);
battArray.shift();
battArray.push(batt);
</script>
</head>
<body>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select date_time, battery_voltage_mv FROM measuring_device_statuses order by date_time desc limit 12");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
/*
echo "<pre>".print_r($WData, true)."</pre>";
die();
*/
?>
<script>
var WData = <?php print_r(json_encode($WData));?>;
//console.log(WData);
dspChrt(WData);
</script>
</body>
</html>
Keep you data fetch php script in some file "fetch.php" and through javascript set interval function call it periodically for example this code prints alert every 3 secs.
setInterval(function(){ alert("Hello"); }, 3000);
You can use AJAX for this purpose.
HTML
<div id="myDiv"></div>
JavaScript
<script>
window.onload = function(){
loadDoc();
SetInverval(loadDoc, (10000 * 60 * 15)); // Perform function every fifteen minutes
}
function loadDoc() {
var div = document.getElementById("myDiv"); // Get Div
div.innerHTML = ""; // Set to nothing
var xhttp = new XMLHttpRequest(); // Create new XML object
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // If successful
div.innerHTML = this.responseText; // Display result
}
};
xhttp.open("GET", "loadDoc.php", true);
xhttp.send();
}
This should be in your PHP file, named loadDoc.php or whatever you choose to replace it to.
<?php
require("Connection.php");
$stmt = $conn->prepare("SELECT date_time, battery_voltage_mv FROM measuring_device_statuses ORDER BY date_time DESC LIMIT 12");
$stmt->execute();
//$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
$stmt->close();
echo "<pre>".print_r($WData, true)."</pre>";
die();
?>
I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..
My php -
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer <= 0){
}else{
echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
echo '<div id="user">#'.$user.'</div>';
echo '<div id="timer">'.$timer.' </div>';
}
}
}
I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.
As per my comment, you could do something like this:
Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
Create php script which returns new $timer whenever it's called:
ajax-timer.php
<?php
/* include file where $conn is defined */
$response = array();
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer > 0) {
//Add just timer to response array
$response[] = $timer;
}
}
}
//Return json response and handle it later in ajax:
echo json_encode(array(
'result'=>empty($response) ? 0 : 1,
'data'=>$response));
die();
Request data from ajax-timer.php with $.ajax and populate data when response is received:
timer-update.js
var ajaxTimerThread = 0;
var ajaxTimerRunning = false;
function ajaxTimerRun() {
//Prevent running function more than once at a time.
if(ajaxTimerRunning)
return;
ajaxTimerRunning = true;
$.post('ajax-timer.php', {}, function (response) {
ajaxTimerRunning = false;
try {
//Try to parse JSON response
response = $.parseJSON(response);
if (response.result == 1) {
//We got timer data in response.data.
for(var i = 0; i < response.data.length; i++) {
var $timer = $('.timer').eq(i);
if($timer.length) {
$timer.html(response.data[i]);
}
}
}
else {
//Request was successful, but there's no timer data found.
//do nothing
}
//Run again
ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
}
catch (ex) {
//Could not parse JSON? Something's wrong:
console.log(ex);
}
});
}
$(document).ready(function() {
// Start update on page load.
ajaxTimerRun();
})
Toss your existing php code into a separate .php file
Then use a jquery method called load() to load that php file into your div.
$(document).ready(function() {
$("#div_ID_you_want_to_load_into").load("your_php_file.php");
var pollFrequency = function() {
if (document.hidden) {
return;
}
$("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
};
setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});
Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.
Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.
How can I enter the dynamically created input fields in my database using php?
Code snippet explanation:
Firstly the user enters the date1 and date2 values. The javascript code creates dynamic input fields. Then on submitting the values mysql query executes.
Problem is the mysql query is not able to enter the dynamic values into database.
JS:
function getrates() {
var date1 = Date.parse(document.getElementById('date1').value); //taking input from user
var date2 = Date.parse(document.getElementById('date2').value);// taking second input from user
var no_of_days = ((date2-date1) / (1000 * 3600 * 24)); //calculating days b/w date1 and date2
//document.getElementById('nod').value = no_of_days;
var newDateColumn;
var newRow;
var table_columns = 2;
for(counter = 1; counter<= no_of_days; counter++) {
newDateColumn = document.createElement("td");
newDateColumn.innerHTML = "Day "+counter;
newAmtColumn = document.createElement("td");
newAmtColumn.innerHTML = "<input type='text' class='form-contol' name='txt"+counter+"'>";
newRow = document.createElement("tr");
newRow.insertBefore(newDateColumn, newRow.appendChild(newAmtColumn));
//newRow.appendChild(newAmtColumn);
document.getElementById("ratetab").appendChild(newRow);
} }
HTML:
<label>Date1</label>
<input id="date1" name="date1" type="text" placeholder="yyyy/mm/dd">
<label>Date2</label>
<input id="date2" name="date2" type="text" placeholder="yyyy/mm/dd" onchange="getrates();">
<table id="ratetab" class="table">
<tr>
<th>Date</th>
<th>Rates</th>
</tr>
</table>
PHP:
<?php
$conn = new PDO('mysql:host=localhost;dbname=ratebox', 'root', ''); //db connection
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$d1 = new DateTime("$date1");
$d2 = new DateTime("$date1");
$no_of_days = $d1->diff($d2)->days; //calculating no of days
for ($x = 0; $x < $nO_of_days; $x = $x + 1) {
$rate = $_POST['txt' + counter];
$conn->query("insert into tb_rate(rates) values (NOW(),'$rate')") or die(mysql_error());
}
?>
I am not able to enter the input values into database.
You have syntax error in your mysql query.
"insert into tb_rate(rates) values (NOW(),'$rate')"
Here you should have two parameter in as table column and you have passed only one. This query should be something like.
"insert into tb_rate(date_field, rates) values (NOW(),'$rate')"
May this help you.
The below is my 2 cents on the DB only routines. I hope it is useful.
<?php
$date1 = $_POST['date1'];
$date1 = $_POST['date2'];
$d1 = new DateTime("$date1");
$d2 = new DateTime("$date1");
$no_of_days = $d1->diff($d2)->days; //calculating no of days
try {
$conn = new PDO('mysql:host=localhost;dbname=ratebox', 'root', ''); //db connection
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <--- non-production mode, debug
// figure out what some_column is below in your table
$stmt = $dbh->prepare("INSERT INTO tb_rates (some_column,rates) VALUES (now(), :col2)");
$stmt->bindParam(':col2', $rate);
for ($x = 0; $x < $nO_of_days; $x = $x + 1) {
$rate = $_POST['txt'] + counter; // <--- is that better ?
// problem: $rate still has uncleansed user-supplied data
// the next line probably has an error. 1 column versus 2 columns in the values():
//$conn->query("insert into tb_rate(rates) values (NOW(),'$rate')") or die(mysql_error());
$stmt->execute();
}
}
catch (PDOException $e) {
// non-production mode, debug
print "Error!: " . $e->getMessage() . ".";
die();
}
// when are you closing that $conn by the way? Something to think about
?>
Also don't connect with root unless in maintenance-mode. Use prepare and bind with PDO, not passing strings from user-supplied values. What is the point of using PDO otherwise?
So basically, you are combining mysql_* deprecated concepts, error trapping, with PDO, like a cut-and-paste jumble of code. Still allowing for sql-injection imo.
i've built a basic countdown timer in PHP which will echo the result back to be displayed on page by javascript every second (or every minute, I havent decided if doing a get call every second will cause any issues yet)
So the countdown works by taking input from a user and updating a DB serverside. PHP then takes this value, converts it into a time format and uses it to calculate the end time for the countdown.
My question is, I would like the timer to flash or something similar when the time changes based on new DB input... So for example the timer would be counting down to 2 hours. Another user submits the form which updates the database so now the end time is 5 hours away. Id like to somehow capture this change so I can display a message on the page.
I'm wracking my brains about how to do this but cannot think of a method.
basic PHP im using to calculate the end time
<?php
$timeUntil = 100; // placeholder, actual variable will be integer pulled from db
$unixTime = 86400;
$zTime = $timeUntil * $unixTime;
$endDate = time() + zTime;
$remaining = $endDate - time();
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
$minutes_remaining = floor((($remaining % 86400) % 3600) / 60);
$seconds_remaining = floor((($remaining % 86400) % 3600) % 60);
$zTimeCombined = array($days_remaining, $hours_remaining,
$minutes_remaining, $seconds_remaining);
echo $zTimeCombined;
?>
I would personally use websockets for this. Doing too many AJAX requests is the best way to kill your server. What you need for this is Ratchet on the PHP-side and WebSockets (no lib needed) on the JS-side.
On the server, onOpen, you would send the current timer time and you would send a new message to every client if the time is updated.
Here is a small example:
composer.json:
{
"require": {
"cboden/ratchet": "^0.3.3"
},
"autoload": {
"psr-4": {
"App\\": "App/"
}
}
}
socket.php:
<?php
require 'vendor/autoload.php';
use App\Chat;
use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
$var = new Chat;
$var = new WsServer($var);
$var = new HttpServer($var);
$var = IoServer::factory($var, 8080);
$var->run();
App/Chat.php:
<?php
namespace App;
use Ratchet\MessageComponentInterface;
use SplObjectStorage;
use Ratchet\ConnectionInterface as Connection;
use Exception;
class Chat implements MessageComponentInterface
{
public $clients;
public function __construct()
{
$this->clients = new SplObjectStorage;
}
public function onOpen(Connection $conn)
{
$this->clients->attach($conn);
}
public function onMessage(Connection $from, $msg)
{
foreach ($this->clients as $key => $value) {
if ($value != $from) {
$value->send($msg);
}
}
}
public function onClose(Connection $conn)
{
$this->clients->detach($conn);
}
public function onError(Connection $conn, Exception $e)
{
echo 'error: ' . $e->getMessage() . "\n";
$conn->close();
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Chat</title>
</head>
<body>
<div id="chat"></div>
<input type="text" id="input">
<input type="submit" id="submit">
<script type="text/javascript">
var socket = new WebSocket('ws://localhost:8080')
socket.onmessage = function (msg) {
addToChat(msg.data)
}
var input = document.getElementById('input')
var submit = document.getElementById('submit')
submit.addEventListener('click', function (e) {
e.preventDefault()
if (input.value.length > 0) {
addToChat(input.value)
socket.send(input.value)
input.value = ''
}
})
function addToChat(msg) {
document.getElementById('chat').innerHTML += '<p>' + msg + '</p>'
}
</script>
</body>
</html>
This is the socket Hello World: a chat. It is in it's simplest form, just a message sent, no username, time, etc. It basically is the Ratchet example but adapted to WebSockets.
To go further, do not hesitate to rely on documentation (Ratchet and MDN for JS-side).
as the title says, is it possible to refresh a div without another html or php page inside of the div?
for example this is what can be done using javascript:
$(document).ready(function () {
$('#mydiv').delay(10000).load('page.php');
});
My Div shows/holds a data which is pulled from the mysql database and it doesn't have page.php inside it.
I've searched for this and all the results were similar to the one i posted above!
is this even possible and if so how?
EDIT:
the data that currently is displayed in the DIV is the $end_time for an item. the $end_time is basically a datetime which is stored in the mysql database. the $end_time already is ticking (a countdown timer using javascript). There is button which whenever pressed, 1 minute Will be added to the $end_time in the mysql.
But when the button is pressed I need to refresh/re-load the page in order to be able to view the changes (in this case 1 minuted added to the countdown timer).
what I need to do is to reload the DIV once that button is pressed so all the users can see that 1 minute has been added to the countdown timer WITHOUT reloading or refreshing the page.
EDIT:
Here is my full code, this works as it should and it will pull the data from mysql database as it should so I have no problem with this part of the project:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('Europe/London'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
<?php echo $dynamicList; ?>
<script src="ajax_link.js" type="text/javascript"></script>
<div id="ajaxlink" onclick="loadurl('timeadder.php')">Click here</div>
<input type="submit" name="ajaxlink" id="ajaxlink" value="Submit" onclick="loadurl('timeadder.php')"/>
and Here is the code for the page that will add the 1 minute to the database and this owrks fie as it should too:
timeadder.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$sql = "UPDATE item SET end_date = DATE_ADD(end_date,INTERVAL 1 MINUTE) WHERE id = 1;";
$query = mysqli_query($db_conx, $sql);
?>
All i need to do is to refresh the DIV countdown that holds the timer.
I hope someone now can help.
The question is unclear, but if your were trying to periodically load a php into a div it could be done with setInterval
setInterval(
function(){
$('#mydiv').load('page.php');
},10000);
EDIT:
Ok then Id suggest Jquery.get
setInterval(function(){
$.get('page.php',function(timerValue){
$('#mydiv').html(timerValue);
});
},1000);
Modified to integrate newly posted code in OP:
In your while{} statement, you are sticking div tags around the end date, but there is no easy way to identify which item's end date the div belongs to.
Suggestion:
$dynamicList .= '<div id="ed-' .$id. '">' . $end_date . '</div>';
That will create a uniquely named div around each end date. Now, you can access a specific end date via jQuery, thus:
$('#ed-3').html(newdata);
Also, shouldn't this:
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
Be like this:
<div id="result"><div id="countdown"><?php echo $end_date; ?></div></div>
</br>
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var item_id = 0;
$(document).ready(function() {
$('#mybutt').click(function() {
item_id = $(this).attr('id').split('-')[1];
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'getenddate.php`,
data: `item=` + item_id,
success: function(fromPhp) {
$('#countdown').html(fromPhp);
//or, to change this item's end date as echoed out from $dynamicList:
//$('#ed-' + item_id).html(fromPHP);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="countdown"></div>
<input id="item-12" type="button" value="Add One Minute">
</body>
</html>
PHP: getenddate.php
<?php
//item is NAME of var being posted over (key),
//item_id is the var contents on the client side ONLY
//$_POST['item'] is var contents (value) as it arrives on PHP side
$itemid = $_POST['item'];
// ** FIXME the query contains a SQL injection vuln,
// ** please untaint $itemid before using
//code to return current time value from database - runs every time
$end = mysql_result(mysql_query("SELECT `end_date` FROM item WHERE `id` = '$item' "), 0);
echo $end;
If I understood you right, you want to change the content of a DIV, no matter what is inside. This can be accomplished like this:
in the HTML you have something like:
<div id="mydiv">My old content, no sites here</div>
An in the JS(jQuery enabled) you do (for example in the ready function):
$(document).ready(function () {
$('#mydiv').html("This content is brand new");
});
jsFiddle of the code above
The .html() function deletes the old content of that tag and replaces it with new content.
If you, for example, want to show the current seconds, you can do as follows:
$(document).ready(function () {
setInterval(function(){
// change time
$('#mydiv').html("Seconds: "+ new Date().getSeconds());
},1000);
});
jsFiddle of the code with counter
This should be almost exactly what you are looking for (untested):
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var adder = 0; //Global var -- outside document.ready
$(document).ready(function() {
$('#mybutt').click(function() {
adder++;
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'myphpprocessor.php',
data: 'addval=' + adder,
success: function(fromPhp) {
$('#theTimer').html(fromPhp);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="theTimer"></div>
<input id="mybutt" type="button" value="Add One Minute">
</body>
</html>
PHP: myphpprocessor.php
<?php
$howmuch = $_POST['addval'];
if ($howmuch > 0) {
//code to update database by the amount
// - only runs if howmuch has a value
}
//code to return current time value from database - runs every time
$thetime = mysql_query('SELECT etc etc etc');
echo $thetime;
Notes:
The database only needs to store the number of minutes to be added to the current time
Your PHP code can then:
(a) Query the DB for number of mins to add: $num_mins_to_add
(b) Create a new date object with current time
(c) Add the $num_mins_to_add to (b)
(d) ECHO back the value