I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.
Related
I have a php code as shown below in which session timeout happen after 60 mins when there is no activity. The following code is inside the file /mno.php. My login and logout code is also in the same file /mno.php.
/mno.php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
header('location: /mmo.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
The table trace_users in the code keeps the track of all logged in users. In that table, there are two columns user_name and open. The value is set to true/false when any user log in/log out.
I have included sql query in which I am trying to update a table when there is no activity but unfortunately the column value is not getting set to false for that particular user when no activity happens for 60 mins.
This is what I have tried:
After doing some research, I think I have to run a timer (js/ajax). In the javascript shown below I have calculated the difference between the Last Activity and the Current time.
If its more than 60 mins, then it will update a db table. This is what I have tried but I believe more need to be done in order to update a table in db.
<script>
let x = setInterval(function() {
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>
let now = <?php echo time() ?>;
let difference = now - lastActivity;
if (difference > 3600) {
clearInterval(x);
}
}, 1000
);
</script>
Problem Statement:
I am wondering what changes I should make in the js (or php) code above so that when there is no activity for 60 mins, it should update the column open to false (in the table trace_users) for that particular user.
Edit 1:
My login code and session history code is in the same file /mno.php. I have placed everything in the same file /mno.php.
I think Vineys and jo0gbe4bstjbs answer is wrong because of when user close browser until 5 seconds, it can't update table after 60 mins and session too. Session deletes just after time in where set in php.ini configuration file.
And Do you mind requesting every 5 seconds is it good way to solve this? It is worst for performance.
If you want solve this problem with professionalism, you should add "last_request" column and delete "open" column from the table and after every request you should update last_requests value to current unix timestamp. And where getting users you should write:
$time = time() - 3600;
"SELECT * FROM `users` WHERE last_request > $time" //active users
"SELECT * FROM `users` WHERE last_request <= $time" //inactive users
And instead of ajax request every 5 seconds you should write setTimeout with 3600 second delay time which run window.location.href= '/mmo.php'; code.
Its way good if you want best performance and exactly result with 60 minute logout
I suppose you realize that this code
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
//...
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
runs on every request and only when a request arrives
Imagine I visit your website and then go out shopping keeping the browser open. What do you think will happen?
NOTHING - because there will be no new request sent to you (assuming you haven't implemented any periodic ajax polling / Websocket mechanism)
So the server won't bother about me until I come back from shopping and refresh the page, only then would the server realize "Hmmm..This guy's LAST_ACTIVITY is older than an hour let me update my trace_users table and set open as false for him"
Coming to your proposed solution, it looks good and avoids the complications of websockets/periodic ajax requests
Just need some minor corrections, follow here for a basic demo
<script>
var lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
var now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server
// but later on it will be incremented by javascript to act as counter
var logoutAfter = 5; //I set 5 sec for demo purposes
var timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
}
}, 1000);
</script>
Here the lastActivity will hold the timestamp when the page was sent by server to browser it will be never changed by scripts on the browser,
now is your counter that you will use to track how much time passed since page was loaded on the browser, you'll increment it every second and check if a given amount of time has been crossed
If true do a ajax request (or simply redirect to logout.php) where you would destroy session and update the trace_users table to mark the user as closed
UPDATE
So ajax will be like
$.ajax({
url: "/close.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
window.location.href= '/mmo.php';
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
and
close.php
<?php
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
// I'm not sure whether the below if condition check is required here or not
// because we have already checked (whether to timeout or not ) in our javascript
// and we call close.php only when it's affirmative
// I encourage you to test and find out :)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Page.php
<!-- CODE TO INCLUDE IN HEADER.PHP -->
<?php
session_start();
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!-- CLOSE -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
let now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server+
// but later on it will be incremented by javascript to act as counter
let logoutAfter = 5; //I set 5 secs for demo purposes
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/mmo.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("I am inside error");
alert(textStatus);
}
});
}
}, 1000); //<-- you can increse it( till <= logoutAfter ) for better performance as suggested by #"Space Coding"
</script>
</html>
mmo.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name'])?$_SESSION['user_name']:'';
$stmt->bind_param('ss', $open, $usname );
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
This is a simple time validation for web page:
$modified_on = isset($SERVER['HTTP_IF_MODIFIED_SINCE']) ? $SERVER['HTTP_IF_MODIFIED_SINCE'] : null;
$current_time = time();
if (!is_null($modified_on) && ($current_time - strtotime($modified_on)) > 3600) {
session_destroy();
...
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $current_time).' GMT');
...
On my php website I have many various countdowns. These are only updated when the user refreshes the page. I want to change it so that the countdown is continous.
I have found many javascript codes that perform this, however I'm unsure how to implement my php code into there script.
Please see below scripts:
My php function for timer:
function countup ($online){
global $time;
$difference=$online-$time;
$num = $difference/86400;
$days = intval($num);
$num2 = ($num - $days)*24;
$hours = intval($num2);
$num3 = ($num2 - $hours)*60;
$mins = intval($num3);
$num4 = ($num3 - $mins)*60;
$secs = intval($num4);
if($days != 0){echo"$days days, ";}
if($hours != 0){echo"$hours hours, ";}
if($mins != 0){echo"$mins minutes and ";}
echo"$secs seconds";
}
where I show the timer I have the following.. <?=countup($set[ends])?>
Ends = future unix timestamp.
The javascript countdown I came across was from http://keith-wood.name/countdown.html but I have no understanding of java and am not sure how to put $set[ends] into it!
All help would be greatly appreciated!
Considering, that you're loading all required scripts properly, here is what I would suggest:
PHP part
$ends = date("Y, n-1, j", $set[ends]); //covert your time stamp to the required format
**JavaScript Part **
<script type='text/javascript'>
( function( $ ) {
$('#yourCountDownDIV').countdown({until: <?php echo $ends ?>});
} )( jQuery );
</script>
Put the JavaScript part at the end of the HTML code just before the closing tag and after all your JavaScript files are loaded.
Hey guys am really a noob in php...I just want to make a redirect after the session ends..So i have came to know that without js this cant be implemented..So i have modified the code with the help of my friends
<html>
<body>
<?php
session_start();
$_SESSION['logintime'] = time();
echo 'this page needs to be redirected in a minute'
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
$(function(){
var loginTime = <?php echo $_SESSION['logintime']; ?>
var testSession = setInterval(function(){
var currentTime = Date.now() * 1000;
if((currentTime - loginTime) > 60) { //here 60 denotes a minute
<?php session_start();
session_unset();
unset($_SESSION);
session_destroy();
?>
window.location.href = 'www.google.com'; // redirecting process
}
}, 1000);
});
</script>
</body>
</html>
The code runs without errors ..but it isnt redirecting after 60 seconds..
Any guides to make this code work correct would be really appreciated..Thanx
Try this, it goes in the section of your html:
Using html only
<meta http-equiv="refresh" content ="5; url=http://www.target.com/">
5 is the number of seconds. Now you can replace 5 with some PHP generated value.
<meta http-equiv="refresh" content ="<?php echo $limitTime(); ?>; url=http://www.target.com/">
If you want to do it in Javascript use following syntax
setInterval(function () {window.location.href = 'http://www.google.com'}, 60000)
In php you can use header method to redirect url
header("Location: http://www.google.com")
I am using a pure JavaScript count down timer that I shared below to redirect to a URL after some time and show the left time to visitor also.
DEMO: JSFiddle
<form name="redirect" id="redirect">
You Will Be Redirected To Next Page After <input size="1" name="redirect2" id="counter"></input>Seconds.
</form>
<script type="text/javascript">
var countdownfrom=5
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
showIt()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
function showIt() {
window.location.href = "http://jsfiddle.net/";
}
</script>
Now I want the same function and features and work in pure PHP as you know that many old mobile browsers still does't not support JavaScript and many are using JavaScript blocker. So Is this possible to do the same in Pure PHP, no <script> tags.
UPDATE:
I know the below codes but I want a count down timer too to show to the visitor.
<?php header('Refresh: 5; URL=http://jsfiddle.net/'); ?>
<meta http-equiv="refresh" content="5;url=http://jsfiddle.net/">
Answer:
This can't be done only with php you will need to use jquery or javascript with it. PHP is a server side scripting language you have to use client side language for this task.
Tip:
For redirecting purpose Just use header() function in php to redirect the php file in some time.Your code should look like this
<?php
header( "refresh:5;url=http://jsfiddle.net" );
?>
Hope this helps you...
Well if you want some output, you can't use header(). Alternatively, you could do something like this:
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 0;
while($x <= 4) {
$x++;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
PHP is a server-side language. You cannot control how the browser behaves from PHP without some quite complex setup. And even that, you cannot guarantee the behaviour of showing a countdown without JavaScript. For browsers who restrict JavaScript execution, the Refresh header will work just fine. However, for those having JavaScript enabled (which is the majority of browsers nowadays, desktop and mobile alike), a simple header will not give any UI feedback and is frustrating for users who expect responsive applications and web pages.
For this reason, JavaScript can be added, if available, to enhance the automatic, delayed, redirection and give the user some feedback of what's going on. Those with JavaScript disabled will just see a static page, telling them that the page will be redirected, and how long they have to wait for it.
PHP
<?php
$redirectTimeout = 5; // seconds
header('Refresh:' . $redirectTimeout . ';url=http://jsfiddle.net');
// ...
// inside your <head>, add this
echo '<meta http-equiv="refresh" ' .
'content="' . $redirectTimeout . ';url=http://jsfiddle.net">';
// ...
// inside your <body>, add this (or something similar)
echo '<div>' .
'You will be redirected to next page after ' .
'<span id="redirectCountdownLabel">' .
$redirectTimeout .
'</span> seconds' .
'</div>';
// ...
// add JS below
JavaScript
For this part, I recommend you use jQuery. It will not only write safer and cross-browser JS, it will also make your code smaller and prettier. This part can be put anywhere in your HTML, or inside a .js file that you add with a <script> tag. For convenience, you can even add jQuery using a CDN.
!function() {
$(function () {
var meta = $('head meta[http-equiv="refresh"]');
var label = $('#redirectCountdownLabel');
var loadTime;
var refreshTimeout;
if (meta.length && label.length) {
loadTime = window.performance.timing.domComplete;
refreshTimeout = parseInt(meta.attr('content'), 10); // seconds
new Timer(refreshTimeout * 1000, loadTime).start(200, function (elapsed) {
// "elapsed" ms / 1000 = sec
label.text(refreshTimeout - parseInt(elapsed / 1000));
});
}
});
function Timer(maxTime, startTime) {
var timeout;
var callback;
startTime = startTime || Date.now();
function nextTimer(delay) {
timeout = setTimeout(function () {
var curTime = Date.now();
var elapsedTime = curTime - startTime;
callback(elapsedTime);
if (elapsedTime < maxTime) {
nextTimer(delay);
}
}, delay);
}
this.start = function start(ms, cb) {
stop();
callback = cb;
nextTimer(ms);
};
this.stop = function stop() {
if (timeout) {
clearTimeout(timeout);
}
};
};
}();
(Note: here's a jsfiddle of the Timer class.)
scusate per prima, ho postato male, sono ali inizi, sorry
<?php
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
To do the countdown, so it seems to work or am I wrong?
<?php
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh"content="0;url=http://jsfiddle.net/">';
?>`
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