jquery countdown changes when user change its system time - php

i'm using jquery countdown with php. i have given an end date which is going to the countdown. my problem is lets suppose 1 hour left is showing in countdown but when a user change its system time the countdown changes. like if a user back his time 1 hour then the counter will display the 2 hours left. is there any way to get the server time for more accurate time not the user system time. please help.
how can i get server time not user system time?
below is my jquery code
if($(pluginsArray[6]).length){
$(pluginsArray[6]).each(function(){
var $this = $(this),
dateObj = $this.data();
var finalDate = new Date(dateObj.year, dateObj.month, dateObj.day, dateObj.hours, dateObj.minutes);
$this.countdown({
timezone: +4,
until : finalDate,
expiryText: '<div class="over">Closed.</div>',
onExpiry : function(){
setTimeout(function( ) { location.reload(); }, 5000);
},
format :'DHMS',
layout : '<b>{dn}</b> <span class="fs_medium d_inline_b m_right_5">days</span> <b>{hn}</b> <span class="fs_medium d_inline_b m_right_5">hrs</span> <b>{mn}</b> <span class="fs_medium d_inline_b m_right_5">min</span> <b>{sn}</b> <span class="fs_medium">sec</span>'
});
});
}
and here is what i did in php
<div class="countdown color_redc d_inline_m fs_large second_font lh_small f_xs_20" style="font-size:26px;" data-year="<?= $aDate[0] ?>" data-month="<?= ($aDate[1] - 1) ?>" data-day="<?= $aDate[2] ?>" data-hours="<?= $aDate[3] ?>" data-minutes="<?= $aDate[4] ?>"></div>

Solution without PHP
What you can do, without coding any server side is using a public API to get current time.
Found a similar topic on StackoverFlow : Free Rest API to get current time as string (timezone irrelevant)
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for
a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
GenoNames looks to be US only, TimezoneDb works you just need to register for a free public key.
Few people recommend timeapi.org but looks like they do not accept CROSS-DOMAIN request in Ajax, and the exemple they provide is no longer available.
Solution with PHP and jQuery Countdown configuration
Also you can ask jQuery CountDown to synchronyze with your server using serverSync option
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
PHP file : serverTime.php
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
BUT
Keep in mind your user will always be able to change your code and fake it ... so if you need to implement some security this is not enough and you will need to code some backend stuff.

Related

show and hide based on server date and time

So here's what I'm trying to do - I have the following code:
<div id="on">
<p>We are: <span class="onair">ON AIR</span></p>
</div>
<div id="off">
<p>We are: <span class="offair">OFF AIR</span></p>
</div>
And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.
?
If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.
(Client side solutions work too if you dont care about where the time is coming from)
(1) You can have the server render javascript for you that you can use in a script
//if you want the server's time you can do this:
<?php $timestamp = time(); ?>
//render variables in javascript instead of html
<?php
echo <<<EOD
<script>
var timestamp = ${timestamp}
//then later in your javascript process the timestamp logic to update the dom
</script>
EOD;
?>
(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)
//onAirClass( min, max, timestamp ) returns className
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
if( timestamp >= timeMin && timestamp <= timeMax ){
return 'onair';
}
return 'offair'
}
//using onAirClass( min, max, timestamp )
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>
then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.
Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function
How to check the time between a given time range
UPDATED
Corrected PHP syntax errors
#maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:
var timestamp = $('#server-timestamp').text();
Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.
There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:
is simple
is efficient (doesnt do anything unnecessary or redundant)
falls in line with best practices
Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.
Here's a function you can use:
var onAir = function (day, start, end, timezone) {
var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;
// by default, we are not on air
onAir = false;
// map day numbers to indexes
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];
// convert start/end times to date objects
startValues = start.split(':');
endValues = end.split(':');
startTime = new Date();
endTime = new Date();
startTime.setHours(startValues[0], startValues[1]);
endTime.setHours(endValues[0], endValues[1]);
// add the hours minutes together to get total minutes
startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();
// get the current local time
local = new Date();
// get the current time in the show's timezone
utc = local.getTime() + (local.getTimezoneOffset() * 60000);
show = new Date(utc + (3600000*timezone));
// convert the show hours + minutes to just minutes
showMinutes = (show.getHours() * 60) + show.getMinutes();
// test to see if the show is going on right now
if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
onAir = true;
}
return onAir;
}
// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));
// now check if we are on air
if (texasShowOnAir) {
// do stuff here...
}
You can now use this function like this:
var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');
This will return a true/false. Be sure and use 24 hour format.
I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.
Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/
Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.
Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.
From the server:
<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>
On the client:
$(document).on('load', function() {
var serverTime = new Date($('#server-timestamp').text())
, clientTime = new Date()
, offsetMilliseconds = (clientTime - serverTime);
setInterval(function() {
// If server time is 3pm-4pm then hide/show divs...
}, 1000 /* every second */);
});

Refresh div, but only if there is new content from php file

Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds

JQuery and PHP Date difference

I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client

Is my code a performance killer?

I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?
Thank you.
index.php
<script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );
$(function() {
SANAjax = function(){
$('#dataDisplay').load('timer.php');
}
});
</script>
<div id="dataDisplay"></div>
timer.php
function time_difference($endtime){
$days= (date("j",$endtime)-1);
$hours =date("G",$endtime);
$mins =date("i",$endtime);
$secs =date("s",$endtime);
$diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
return $diff;
}
$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>
Depends on your server specs and number of clients, this could quickly become a server-killer.
The multiple calls to a file every second will quickly put a lot of load for nothing though, so best practice calls for using a javascript timer countdown. I particularly like this one: http://stuntsnippets.com/javascript-countdown/
And for the jQuery implementation:
<script type="text/javascript">
var myDate = new Date(); //Retrieve actual date
myDate.setTime(this.getTime() + (3600 * 2)); //Add two hours
$(document).ready(function() {
$("#time").countdown({
date: myDate.toGMTString(),
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
This should be enough, no more need for PHP calls and the client does everything.
By setting a setInterval for every second, you are basically saying that for 30 clients, you will be getting roughly 30 txn per second to your php server. Its hard to say its a performance killer outside of just saying you will have to handle 30tps for this simple call. I would first quesiton why you are doing this with a server side script. You could just as easily give the html file a datetime when the page loads and do the countdown with just javascript in the browser.
I use jQuery Countdown http://keith-wood.name/countdown.html to put a timer on my pages to let the user know when they are going to be logged out of the system due to inactivity.
You can bind a function to the counter expiring event.
http://code.google.com/p/jquery-countdown/ ...Simple example
http://keith-wood.name/countdown.html ...shows off all the bells and whistles...
It can be as simple as the first one or as detailed as the second!
-=Bryan

Jquery Countdown Server sync issue

I'm trying to create a countdown for an event. I'm using Jquery Countdown
I have this code:
$(function () {
var fecha = new Date("July 30, 2011 00:00:00");
$('#defaultCountdown').countdown({
until: fecha,
format: 'DHMS',
expiryUrl: "http://www.google.com",
serverSync: serverTime,
timezone: -4
});
});
function serverTime() {
var time = null;
$.ajax({
url: 'serverTime.php',
async: false,
dataType: 'text',
success: function (text) {
time = new Date(text);
},
error: function (http, message, exc) {
time = new Date();
}
});
return time;
}
The script is working fine, but when I try to change the clock date, the countdown changes.
Any idea why?
I imagine you created the serverTime.php file on your server?
http://keith-wood.name/countdown.html
Tab Timezones has the PHP code you'll need to add to serverTime.php for your script to use that. Also may want to fully qualify that to something like url: 'http:yourdomain.com/serverTime.php' But using that it should use your server time not your local PC time. If your server is on your local PC, then well... it would change.
I went to their site, with their example, and changing my system time affects their countdown as well. Their code relies on local system times.
What I see when you get the server time form the ajax call, it is not creating the JavaScript date object.
I searched and below worked for me.
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
alert(d);
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)

Categories