I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>
Related
I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>
I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Consider an AJAX call that writes to a div:
recent_req=$.post('result.php', { d: data }, function(returnData) {
$('#content').html(returnData);
});
The PHP script at result.php performs some functions that take time, about 5-20 seconds per step. I am using PHP's flush() function to get the info to the browser as soon as each step starts and ends, but how can I get the Javascript to write the data to the #content div as it comes in?
Thanks.
EDIT:
To clarify: Assume result.php looks like the following and due to constraints cannot be practically refactored:
<?php
echo "Starting...<br />";
flush();
longOperation();
echo "Done with first long operation.<br />";
flush();
anotherLongOperation();
echo "Done with another long operation.<br />";
flush();
?>
How might the AJAX be structured to call result.php such that the echo statements are appended to the #content div as they come in? Any solution with / without jQuery is welcome. Thanks!
There's a technique using an iframe which you could use to achieve this.
Similar to other suggestions involving frames but it doesn't involve sessions or polling or anything, and doesn't need you to display the iframe itself. It also has the benefit of running any code you want at any point in the process, in case you're doing something more sophisticated with your UI than just pushing text to a div (e.g. you could update a progress bar).
Basically, submit the form to a hidden iFrame then flush javascript to that frame, which interacts with functions in the iFrame's parent.
Like this:
HTML:
<form target="results" action="result.php" method="post">
<!-- your form -->
<input type="submit" value="Go" />
</form>
<iframe name="results" id="results" width="0" height="0" />
<div id="progress"></div>
Javascript, in your main page:
function updateProgress(progress) {
$("#progress").append("<div>" + progress + "</div>");
}
result.php:
<?php
echo "<script language='javascript'>parent.updateProgress('Starting...');</script>";
flush();
longOperation();
echo "<script language='javascript'>parent.updateProgress('Done with first long operation.');</script>";
flush();
anotherLongOperation();
echo "<script language='javascript'>parent.updateProgress('Done with another long operation.');</script>";
flush();
?>
You cannot 'stream' data using regular ajax calls, for you can't make your user's browser 'listen' to server requests. Your 'success' function will only be called when data's done processing.
There's, though, much discussion on 'Ajax Push' on the internet and apparently HTML5 has websocket objects that can be used to make your user's browser listen to server requests. The syntax definition is not quite stable yet, so you don't want to mess with it, as it may change soon.
What you may want to do is dispatch a request for step1, wait for its return and then dispatch a request for step2. It'll add some overhead to your overall processing time (and will make it much more verbose), but it should work fine if you only have a few big steps. If your steps don't take too much processing, you shouldn't do it (as the communication time will become greater than your 'effective processing time').
EDIT: What you can also do is write the progress on the user's session, for example. That way, you can periodically ping the server with a request for an update on the status. This way, even if you have many small steps, you'll only have to dispatch requests every 10 seconds or so, that being an improvement over dispatching for every step.
As an alternative solution, you could submit a hidden form into an iframe, as shown in the following example:
<?php
function output_data($data) {
echo str_pad($data, 4096, ' ', STR_PAD_RIGHT) . "\n";
flush();
}
function long_runner() {
output_data("");
output_data(date("H:i:s").' - Starting...<br />');
sleep(10);
output_data(date("H:i:s").' - Done with first long operation.<br />');
sleep(10);
output_data(date("H:i:s").' - Done with another long operation.<br />');
return("<script>parent.task_complete()</script>");
}
if (isset($_REQUEST["status"])) {
die(long_runner());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Write to IFRAME as data streams in</title>
<style>
#myform { display: none }
#frm { width: 50% }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function task_complete() {
alert('Task completed');
}
$(document).ready(function() {
$('#starter').click(function() {
$('#myform').submit();
});
});
</script>
</head>
<body>
<form id="myform" method="get" target="frm" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
<input type="hidden" name="status" value="0">
</form>
Start<br />
<iframe id="frm" name="frm" frameborder="0"></iframe>
</body>
</html>
Writing a dynamic data stream to a div:
Here goes.. you asked specifically how to dynamically write data streams to a "div". As many have said it is possible to write dynamically to an iframe and we just need to go one step further. Here is a complete solution to your issue, which will bring that data back to your div with a maximum delay of .5 seconds. It can be adapted if you need a more prompt update.
<!DOCTYPE html>
<html>
<head>
<title>dynamic listener</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var count;
$(function(){
$('#formx').submit(function(){
setTimeout(function(){ check_div(); }, 500);
count = 0;
return true;
});
});
function check_div()
{
var $iframetxt = $('#iframex').contents().text();
var $div = $('#dynamic');
if( $iframetxt != $div.text() )
{
console.log('rewritten!');
$div.text( $iframetxt );
setTimeout(function(){ check_div(); }, 500);
count = 0;
}
else
{
count++;
if(count < 40) setTimeout(function(){ check_div(); }, 500);
else console.log('timed out');
}
}
</script>
</head>
<body>
<div>
Form
<form id="formx" action="result.php" method="post" target="iframex">
<input type="submit" />
</form>
</div>
<div id="dynamic"></div>
<iframe id='iframex' name="iframex" style="display:none" ></iframe>
</body>
</html>
1. On form submit, the streaming data is sent to the iframe.
For this we just set the target attribute in the form tag to the iframe name.
2. check_div() runs every .5 seconds to compare the text of #dynamic div to the text contents of the iframe.
If there is a difference between them, the data is written to the div and the timeout is called again. If there is no difference, the timeout counter increments. If the count is less than 40 (40 x .5 sec = 20 seconds), it calls the timeout again. If not, we assume the stream has completed.
Here is a solution using polling with a session:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var pollTimeout;
function pollResult(){
$.get('poll.php', function(response) {
// Update #content with partial response
$('#content').html(response);
pollTimeout = setTimeout(pollResult, 1000);
});
}
$.post('result.php', function(response) {
// Result is loaded, stop polling and update content with final response
clearTimeout(pollTimeout);
$('#content').html(response);
});
// Start polling
pollResult();
</script>
</body>
</html>
Result PHP:
<?php
class SemiStream{
public function __construct(){
#session_start();
$_SESSION['semi_stream'] = '';
}
public function write($data){
#session_start();
$_SESSION['semi_stream'] .= $data;
// We have to save and close the session to be
// able to read the contents of it in poll.php
session_write_close();
}
public function close(){
echo $_SESSION['semi_stream'];
unset($_SESSION['semi_stream']);
}
}
$stream = new SemiStream();
$stream->write("Starting...<br />");
sleep(3);
$stream->write("Done with first long operation.<br />");
sleep(3);
$stream->write("Done with another long operation.<br />");
$stream->close();
echo 'Done.';
Poll PHP:
<?php
session_start();
echo $_SESSION['semi_stream'];
This works, without the use of PHP's output buffering.
Check out the Pusher service, seems like it could do exactly what you want: http://pusher.com/
Probably, the question is about how to implement Push technology in your app. I would suggest you to look this question which has great answer with example
How to append to textarea with PHP and then refresh the textarea?
THANK YOU
edit:
It should be server triggered from PHP code
The simplest approach would be to have a javascript function that polls the php script using ajax - say every 10 seconds. You could add a timestamp as a parameter to the php function so it only returns the latest log entries.
When the ajax call returns you can append the resulting text to your textarea using javascript.
I could fish out some sample code if you like?
So, here's an HTML file - it has a function to make an AJAX call to a script - log.php that returns some stuff (in this example it's a very simple line of text) and then append this to the text area.
When the script loads we set up a timer to fire every 1000 milliseconds (obviously change this according you your needs).
We've also got a "cancel updates" function and a "start updates".
So - put the html file and the php file (which you need to call log.php - or call it what you like and change the code) into the same directory on your web server and see what happens!.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var http = createRequestObject();
var updateInt=self.setInterval("updateLog()",1000);
function startAutoUpdate(){
if(updateInt==""){
updateInt=window.setInterval("updateLog()",1000)
}else{
stop_Int()
}
}
function stopAutoUpdate(){
if(updateInt!=""){
window.clearInterval(updateInt)
updateInt=""
}
}
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function updateLog(){
http.open('get','log.php');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('log').innerHTML = document.getElementById('log').innerHTML + http.responseText;
}
}
</script>
</head>
<body>
<h2>Log</h2>
<textarea cols="80" rows="10" name="log" id="log"></textarea>
<span onclick="updateLog()">Update</span><br>
<span onclick="stopAutoUpdate()">Cancel Auto Update</span><br>
<span onclick="startAutoUpdate()">Start Auto Update</span><br>
</body>
</html>
Here's the php script (very simple)...
<?PHP
/* Log responder script
*
* When invoked this script returns log entries
* as this is a sample it just returns a couple of random items
*
*/
echo "Log Entry ".date("d/m/y h:i:s")."\n";
?>
i would like to ask how can i make a php script which echoes the id of the data stored in a database repeat itself after specific time for example after 2 minutes.i don't want to use a cron job or another scheduler.Just php or javascript implemantation.Thanks in advance..
I've done similar with this script. While the user is on the page, it runs scriptToRun.php every 2 minutes.
function changeFeedAddress() {
$.ajax({
type: 'get',
url: 'scriptToRun.php',
success: function(txt) {
// do something with the new RSS feed ID here
}
});
}
setInterval(changeFeedAddress,120000); // 2 MINUTES
Alternate to #JMC Creative (Self-contained for example's sake):
<?php
// check if the $.post below is calling this script
if (isset($_POST['ajax']))
{
// $data = /*Retrieve the id in the database*/;
// ---vvvv---remove---vvvv---
// Example Data for test purposes
$data = rand(1,9999);
// End Example Data
// ---^^^^---remove---^^^^---
// output the new ID to the page so the $.post can see it
echo $data;
exit; // and stop processing
}
?>
<html>
<head>
<title>Demo Update</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// assign a timeout for this script
var timeout = 2 * 60000; // 2 minutes
// create a function we can call over and over to fetch the ID
function updateDBValue(){
// call this same script and retrieve an "id from the database" (see top of page)
$.post('<?php echo $_SERVER['PHP_SELF']; ?>',{ajax:true},function(data){
// 'data' now contains the new ID. For example's sake, place the value
// in to an input field (as shown below)
$('#db-value').val(data);
// set a timer to re-call this function again
setTimeout(updateDBValue,timeout);
});
}
// call the function initially
updateDBValue();
});
</script>
</head>
<body style="text-align:center;">
<div style="margin: 0 auto;border:1px solid #000;display:block;width:150px;height:50px;">
DB Value:<br />
<input type="text" id="db-value" style="text-align:center;" />
</div>
</body>
</head>
Why not just do this?
<?php
header('refresh: 600; url=http://www.yourhost.com/yourscript.php');
//script here
?>
If your generating your ID at random from within the script...this will work fine. The page will refresh itself every 10 minutes.