PHP + jQuery change background based on server time - php

I have an Apache based server, which currently hosts my PHP + HTML5 app. I wrote a jquery script, which should change background image of specific div, if some conditions regarding server time are met. Problem is - the script is not working :)
I've already red some issues here, and tried to fix script, but those didn't help, because they are not completely related to my problem.
Ok, here's the script:
$(document).ready(function () {
var serverdate = new Date("<?php echo date('l,g,i,s'); ?>");
var currentTime = serverdate.getTime();
var gameTime = getTimeFromString("8:45 pm");
var endTime = getTimeFromString("11:45 pm");
var currentDay = serverdate.getDay();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
if (currentDay === "Tuesday" || currentDay ==="Wednesday"){
if (currentTime<gameTime) {
$('#bodymain').addClass('day').removeClass('game');
}
else if (currentTime>endTime) {
$('#bodymain').addClass('day').removeClass('game');
}
else {
$('#bodymain').addClass('game').removeClass('day');
}
}
else {
$('#bodymain').addClass('day').removeClass('game');
}
function getTimeFromString(timeString){
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours(parseInt(time[1])+(time[3]?12:0));
theTime.setMinutes(parseInt(time[2]) || 0);
return theTime.getTime();
}
});
Any clues?

I've decided to use a different approach, based on your inputs. Now it all works flawlessly. Here's the final solution (I had to wait until I could answer my own question):
PHP file:
<?php
$current_time = strtotime('now');
if ($current_time > strtotime('tuesday this week 8:45pm') && $current_time < strtotime('tuesday this week 11:45pm')) {
$background = 1;
}
else if ($current_time > strtotime('wednesday this week 8:45pm') && $current_time < strtotime('wednesday this week 11:45pm')) {
$background = 1;
}
else{
$background = 0;
}
?>
<script>
var backday = <?php echo json_encode($background); ?>;
</script>
JS File:
$(document).ready(function () {
createBackground()
});
function createBackground(){
if (backday === 0) {
$('#bodymain').addClass('day').removeClass('game');
}
else if (backday === 1) {
$('#bodymain').addClass('game').removeClass('day');
}
else {
alert("Background error");
}
}

The problem is with serverdate.getDay();.
Date.getDay(); return 0-6 number of day ,not the name of the day.
And serverdate.getTime(); return's number of Miliseconds of the total time.
You should lear about Date Object in JavaScript

Just replace currentDay with weekday[currentDay] because you compare with day name. This will works for you.

Related

php coundown auto update issue

<?php
//index.php
$current_date = date('Y-m-d H:i:s');
$current_min_sec = date('i:s');
$current_min = date('i');
$array_min= array(0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57);
if((int)$current_min >= 57){
$next_slot_time = 0;
}else{
$min = (int)$current_min;
$newNumbers = array_filter(
$array_min,
function ($value) use($min) {
return ($value > $min);
}
);
$next_slot_time = reset($newNumbers);
}
?>
<div id='countdown'></div>
<script type="text/javascript">
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = this.responseText;
document.getElementById("countdown").innerHTML = valr5;
if (valr5 == '00:00'){
window.location = "index.php";
}
}
};
xmlhttp.open("POST", "response.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("next_slot="+<?php echo $next_slot_time?>);
};
updateWind();
window.setInterval(updateWind, 1000);
</script>
<?php
//response.php
$time = new DateTime();
$start_timer_time = $time->format('Y-m-d H:i:s');
$end_minute = $_POST['next_slot'];
if($end_minute == 0){
$timeHr = $time->format("H") + 1;
}else{
$timeHr = $time->format("H");
}
$time->setTime($timeHr,$end_minute,00);
$end_timer_time = $time->format('Y-m-d H:i:s');
$from_time = $start_timer_time;
$to_time = $end_timer_time;
$timefirst = strtotime($from_time);
$timesecond = strtotime($to_time);
$diffinsec=$timesecond-$timefirst;
if(gmdate("i:s",$diffinsec) == '00:30'){
echo 'RUN SCRIPT HERE';
}else if(gmdate("i:s",$diffinsec) == '00:00'){
echo gmdate("i:s",$diffinsec);
}else{
echo gmdate("i:s",$diffinsec);
}
?>
I have a script which shows a countdown with a button and table to the users. it has following things
1] Run countdown every 3 min (exactly 20 times in one hour) 2] Show countdown timing same to all users 3] Never reset countdown on user browser refresh 4] On 00.30 button lock through js and internally another php script runs which does some calculation and updates 1 entry to the table 5] On 00.00 when time over page gets refreshed, the countdown starts again and the below table is shown with newly added entry.
This script is working fine when it is open in the browser but not working when no user is accessing this page. I want to run this countdown offline also. I am figuring out two solutions
1] Make one more script, So it will work when index.php is not open by anyone (but don't know how to track when it should run and when its should not run) 2] Make a single script like (cron) job but in that case how do I display countdown to users
I am not aware of possible vulnerabilities. Kindly share your thoughts. Thanks a lot in advance
Yes. It is only achieve by cron job.. Thanks guys for the support

how to refresh page in a specific time

i tried this code in my wp page but its not work
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
date("d-m-Y H:i:s");
$time= date("H:i:s");
if($time == "03:40:00")
{
echo "The new page loading in 10 seconds!";
header("Refresh: $sec; url=$page");
}
?>
You can't do this in PHP, what you can do for such a task is to calculate a time difference and make it in seconds and set the header for the page to be refreshed after the time diff in seconds, something like this:
<?php
$page = $_SERVER['PHP_SELF'];
$datetime1 = new DateTime('2020-05-23 18:20:10');
$datetime2 = new DateTime('2020-05-23 18:20:30');
$interval = $datetime2->diff($datetime2);
$diff = $datetime2->getTimestamp() - $datetime1->getTimestamp(); // diff in seconds
// you can just have `redirect` queryString params passed like this.
if(empty($_GET['redirect'])) {
header("Refresh: $diff; url=$page" . "?redirect=1");
}
Something to point out here, is to use tag to do the refresh in your page instead of using header(), it feels cleaner to me as implementation, specially if you already have a template engine:
<meta http-equiv="refresh" content="20">
You can place the below code in your header and test. I hope this helps.
if ($time == "03:40:00") {
echo "The new page loading in 10 seconds!";
echo "<meta http-equiv='refresh' content='3'>";
}
Note: The above used meta tag is used to define time intervals to refresh the document itself. Modify the values in "content" attribute of meta tag as you wish to refresh the page
Thank you everyone, problem solved, i used javascript, function auto-run
<script>
(function myFunction() {
var time = new Date().getHours()
if( time == "02" ) {
setTimeout(function(){
window.location = 'your url';
}, 5000);
}
})();
</script>
this code better i think, thank you Andrew Moore !
<script>
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(16,30,0); //Will refresh the page at 4:30pm
</script>

JavaScript countdown from php timestamp difference

I'd like to countdown time which is difference between two time from php, the result is timestamp.
{var $time = new \DateTime()}
<div class="date" data-date="{= ($time2->getTimestamp() - $time->getTimestamp())*1000}">
In data-date I have difference of time [timestamp]. Now I want to countdown this time. I get this information from HTML to JS.
$(function() {
$(".date").each(function(){
time = $(this).data('date');
$.countdown($(this).children(".countdown"), time);
});
});
There is taken code which doesn't work properly.
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
//if(days != 0){out += days +" day"+((days!=1)?"s":"")+", ";}
//if(days == 0) {
if(days != 0 || hours != 0){out += ((hours<10)?"0":"") + hours +":";}
if(days != 0 || hours != 0 || mins != 0){out += ((mins<10)?"0":"") + mins +":";}
out += ((secs<10)?"0":"") + secs;
$(selector).html(out);
//}
// run it all again
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
The time from JS is on the right place but it doesn't countdown.
The answer is very simple: you do not decrease datevalue variable. So its the same for all iterations
Look at the example below it works fine
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
datevalue--;
$(selector).html(datevalue);
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
$.countdown('.date', 10);​​​

Countdown timer built on PHP and jQuery?

After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.
Here's my situation;
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});
HTML:
<div id="this"><?php echo($countdown); ?></div>
My idea is that, every second, #this is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).
I would've though this would have worked, until I realized that the event binder .load() doesn't reload #this (I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?
You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
It is extremely easy to use.
All you have to do is
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});
Here's the fiddle: http://jsfiddle.net/tqyj4/289/
OK, I know that an id is not a variable, but don't use this as an ID. It is makes people cringe.
To the rest, don't reload the value, set a value in JS in PHP and then count down.
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";
Then:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});
Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}
You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.
var timer;
$(document).ready(
name();
);
function name() {
//clear the timer
clearTimeout(timer);
//reset the timer
timer = setTimeout("name()", 1000);
//grab the current time value in the div
var time = $("#this").html();
//split times
var time_splits = time.split(":");
//add up total seconds
var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
//subtract 1 second from time
total_time -= 1;
//turn total time back in hours, minutes, and seconds
var hours = parseInt(total_time / 3600);
total_time %= 3600;
var minutes = parseInt(total_time / 60);
var seconds = total_time % 60;
//set new time variable
var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
//set html to new time
$("#this").html(new_time);
}
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$secondsDiff = $targetDate – $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate && ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>
For more information visit urfusion
#epascarello answer for your question in you need to pass the loop value in selector with id for example
$("#timer<? php echo $loopval; ?>")
and also call the it in the
<div id="timer<?php echo $loopval; ?>">
</div>

How to get time from server using ajax?

I am trying to create a website like penny auction how to display the count down time?
i tried that using ajax, but sometimes it swallow one or two seconds, it shows seconds like 10,9,7,6,3... i mean it doesn't show the proper count down time.. please help me to solve this problem
here is my code
<?php
#session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction = new Auction();
$result=$objAuction -> getStatus();
echo $result;
?>
//ajax code
function getStatusOne(pId)
{
var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
//alert(req.responseText);
var result= req.responseText.substr(1).split("|");
for (var x = 0; x < result.length; x++)
{
var resultN=result[x].split(",");
var prId=resultN[0];
var temp=resultN[1];
var sec=parseInt(temp);
var price=resultN[2];
//alert(prId+' '+temp+' '+price);
var mem=resultN[3];
var img=resultN[4];
var autobid=resultN[5];
if(img=='') {
img='images/profile/no_image.jpg'
}
if(!price)
{
price='0.00';
}
if(!mem)
{
mem='No Bidders Yet';
}
if(document.getElementById("bid_price"+prId))
{
document.getElementById("bid_price"+prId).innerHTML='$'+price;
document.getElementById("bidder_name"+prId).innerHTML=mem;
document.getElementById("userimg").src=img;
document.getElementById("bid_rate").innerHtml=autobid;
if(sec<= -1)
{
sold(prId);
if(document.getElementById('end'+pId))
{
document.getElementById('end'+pId).style.display="block";
}
if(document.getElementById('div_bid_image'))
{
document.getElementById('div_bid_image').style.display="none";
}
if(document.getElementById('clsBidB'+pId))
{
document.getElementById('clsBidB'+pId).style.display="none";
}
}
else {
if(document.getElementById('div_bid_image').style.display == "none")
{
document.getElementById('div_bid_image').style.display="block";
}
if(sec >=0)
{
SetCountdownText(sec,"div_timer"+prId,prId);
}
}
}
}
}
else
{
//alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//php code to calculate time
function getStatus()
{
$selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";
if($this->ExecuteQuery($selProd,"norows") > 0)
{
$auctionArr=$this->ExecuteQuery($selProd,"select");
$auctionName=$this->array2str($auctionArr);
}
return $auctionName;
}
function array2str($array,$level=1)
{
$str = array();
foreach($array as $key=>$value) {
if(is_int($key))
{
$nkey = $key;
$nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
$str[] = $nvalue;
}
}
return implode(',',$str);
}
try this
<?php
$target = mktime(0, 0, 0, 14, 07, 2011) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
print "Our event will occur in $days days";
?>
Assuming you have something like a DIV with the ID "countdown" (to display the countdown in):
Example JavaScript (assumes use of jQuery - recommended):
(function(jQuery) {
updateCountdown("countdown"); // Call on page load
var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);
function updateCountdown(elementId) {
jQuery.ajax({
url: "/ajax/countdown.php?auctionId=123",
type: "GET",
dataType: "json",
success: function(response) {
// Insert value into target element
jQuery("#"+elementId).html(response["timeRemaining"]);
// Stop countdown when complete
if (response["countdownComplete"] == true)
clearInterval(countdown);
}
});
}
Example PHP script (assumed to be at /ajax/countdown.php by the above JavaScript):
<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>
I'd recommend doing all the calculation server side (in PHP) as it has really excellent time/date handling (with lots of built in methods) and requires less code to implement overall.
Have a PHP page echo out the countdown time. And then use something like jQuery's AJAX HTTP Request for that page and populate the response in a DOM element somewhere.
Why do you need Ajax to display the countdown time? Why can't you just display it when the page loads along with the rest of the data?

Categories