Signalling when an updated PHP dynamic clock has received new input - javascript

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).

Related

update database table on session timeout in php

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');
...

How to invoke the function in javascript based on condition

i am trying to send an auto generated mail for wedding event so i have an countdown timer using java script and i want to send a reminder before a day . i tried in php and java script but i am not getting expected output.
Tried below code using java script, but it is not sending /displaying my message on the console
<!DOCTYPE html>
<html>
<p id="demo"></p>
<style>
p {
text-align: center;
color: #7FFF00;
font-size: 50px;
margin-top: 0px;
}
</style>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 3, 2019 10:30:01").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Today is the wedding";
}
var myvar=20;
while(distance==myvar){
document.getElementById("demo").innerHTML = "Reminder";
<?php
//to send an wedding reminder
include "Sendmail.php"
?>
}
}, 1000);
</script>
</html>
Hence i tried with below Php using page auto refresh option:but it is not working as exected-------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("l");
//date_default_timezone_set('America/New_York');
//timezone_name_from_abbr('IHST',19800) for Asia/Colombo
//set the timezone for ist:
date_default_timezone_set('Asia/Kolkata');
$today = date("Y-m-d H:i:s");
$date = "2019-02-26 07:43:16 ";
$tilldate = "2019-02-26 07:43:50 ";
echo $today;
do {
$page = $_SERVER['PHP_SELF'];
$sec = "6";
//echo "Watch the page reload itself in 3 second!";
}while ( $date<=$today)
echo" when satisfied call my function and come out of loop";
break;
//if($today < $date ||$today < $tilldate){
//echo "Watch the page reload itself in 3 second!";
//break;
// echo "Watch the page reload itself in 3 second!";
//include 'FetchData.php';
//}
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
<?php
echo "Watch the page reload itself in six second!";
?>
</html>
It will be very helpful if some one assist me on this.
If your goal is to build a site where people can enter a wedding date, and have it email them a reminder a set time before, you will need to store that data on a server somehow.
If you are familiar with NodeJS you could use it to set up a small app that keeps the wedding dates in memory, (though longer-term storage is safer), and then you can use something like Nodemailer to send the email once the time is reached.
However if you don't know NodeJS, using Javascript alone won't be enough - and you can't call PHP code with JS using an embed like you're doing. Keep in mind that PHP is rendered out before any Javascript is run, so JS can't directly call a PHP function. In order to get JS to communicate with PHP in most cases you'll want to make an AJAX call to a PHP script on your server.
So your front end will be a page that uses JS to send an AJAX request containing a wedding date to a separate PHP script on your server. That PHP script will then save that data to the server, using something like mySQL, (or in a pinch you can just use fwrite( ) to write to the local file structure, though a full database system is safer.)
Now you'll need a 2nd PHP script that checks the data every minute or so, and sends an email when a wedding date is close enough. However, you don't want to use auto-refresh to keep a PHP script running. Instead you'll want to set up a cron task that calls your PHP script however often you need it to.
So the elements you'll need are: 1) HTML page containing Javascript, which sends AJAX data to 2) A PHP script that saves that data to your server, and 3) A 2nd PHP script, called by cron, which checks the data and emails when necessary
On the other hand, if all you need is an email reminder for one specific wedding, you'd probably be better off scheduling it through your email client, or using something like IFTTT.

Time spent by user on webpage

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.

CountDown Timer Before Redirect In Pure PHP

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/">';
?>`

Is it possible to refresh a DIV without another page inside the DIV?

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

Categories

Resources