I have a container div which loops through items in a PHP array to generate repeating element divs all with a unique ID.
I am using a countdown plugin (http://keith-wood.name/countdown.html) to apply to a date on each element and it worked out in PHP.
This all works fine until I load more elements into the page using AJAX /PHP. The countdown isn't applied to the new items and I am struggling to figure out how I would do this.
echo "<div class=\"item\" id=\"item_$id\">
<h4 class=\"name\">$Name</h4>
<p>$Cat</p>";
if ($expires != '') {
$year = date('Y', strtotime($discount['expires']));
$month = date('n', strtotime($discount['expires']));
$day = date('d', strtotime($discount['expires']));
$hour = date('H', strtotime($discount['expires']));
$minute = date('i', strtotime($discount['expires']));
$secs = date('s', strtotime($discount['expires']));
$countdown_html = '<div class="defaultCountdown" id="countdown_' . $id . '" data-year="'. $year .'" data-month="'. $month .'" data-day="'. $day .'" data-hour="'. $hour .'" data-minute="'. $minute .'" data-secs="'. $secs .'"></div>';
echo "<script type=\"text/javascript\">
$(window).load(function(){
var year = $('#countdown_$id').attr('data-year');
var month = $('#countdown_$id').attr('data-month');
var day = $('#countdown_$id').attr('data-day');
var hour = $('#countdown_$id').attr('data-hour');
var minute = $('#countdown_$id').attr('data-minute');
var secs = $('#countdown_$id').attr('data-secs');
$('#countdown_$id').countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
</script>";
}
echo "</div>\n";
}
function loadMoreItems(getQuery, page) {
//load items
$.get(getQuery, null, function(data) {
var container = $(data).find('#container');
if (container) {
var newItemsHTML = "";
newItemsHTML = $(container).html();
var $newItems = $(newItemsHTML);
$container.isotope('insert', $newItems, true);
//add jquery effects to new elements
$newItems.find('.hcaption').hcaptions({effect: "fade"});
$newItems.find(".live-tile").liveTile({pauseOnHover: true});
$('.defaultCountdown').each( function() {
var year = $(this).attr('data-year');
var month = $(this).attr('data-month');
var day = $(this).attr('data-day');
var hour = $(this).attr('data-hour');
var minute = $(this).attr('data-minute');
var secs = $(this).attr('data-secs');
$('#' + this.id).countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
}
}, 'html');
}
After your ajax function returns, just call the jquery to initialise the countdowns again.
Instead of using php to echo the values into the jQuery call - add them to the div itself, e.g
<div class="defaultCountdown" data-year="2013" data-month="11">
Then to initialise it would be:
$('div.defaultCountdown').each( function() )
{
year = $(this).attr('year');
...
$(this).countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
Add some way of checking if an element has already been processed. You could create the elements initially with class="unprocessed"
<div class="defaultCountdown unprocessed">
The countdown initialise function would then be:
$('div.defaultCountdown.unprocessed').each(function(){...})
After the countdown has been initialised remove the 'unprocessed' class name
$(".element").each(function() {
var item_id = "#" + this.id;
if(this.id != 'discount_0'){
container.find(discount_id).remove();
}
$(element_id).countdown({until: new Date($year, $month - 1, $day, $hour, $minute, $secs)});
});
when you are applying countdown you are calling on $(element_id), it should be
$(item_id)
and you are using $year, $month - 1, $day, $hour, $minute, $secs all these are php variables,you cannot use them as jquery variables
Related
first code is for take dates between 2 dates from my table reservas...
<?php
include "controlreservas/conexion.php";
$sql1="select llegada, salida from reservas";
$query = $con->query($sql1);
$r=$query->fetch_array();
$begin = new DateTime( $r["llegada"] );
$end = new DateTime( $r["salida"] );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
?>
<?php foreach ($daterange as $date) : ?>
<?php echo $date->format("Y-m-d"); ?>
this it´s working :
2016-12-20
2016-12-21
2016-12-22
2016-12-23
2016-12-24
Now the next code is for disable this dates (all this dates, only get from the select ) in my datepicker :
<script>
$(function() {
var disabledDays = ["<?php echo $date->format("Y-m-d"); ?>"];
var date = new Date();
jQuery(document).ready(function() {
$( "#datepicker1").datepicker({
dateFormat: 'Y-m-d',
beforeShowDay: function(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray(y + '-' + (m+1) + '-' + d,disabledDays) != -1) {
//return [false];
return [true, 'ui-state-active', ''];
}
}
return [true];
}
});
});
});
</script>
the result is only disables first date, not all dates :
thanks for you time
The variable disabledDates (in javascript) should be an Array of strings, where each string represents a date that you want to disable.
What you can do is create that list from the $daterange variable that you have in php:
$dates_ar = [];
foreach ($daterange as $date) {
$dates_ar[] = $date->format("Y-m-d");
}
$disabled_dates = '"' . implode('", "', $dates_ar) .'"';
And then in your javascript code you can use the $disabled_dates variable (which is a string that contains the values you need:
$(function() {
var disabledDays = [<?php echo $disabled_dates; ?>];
I am currently stuck on a problem and not sure how to solve it. I am new to php and javascript coding so do please correct me if there is an easier way to do this.
My problem is that I am trying to get a countdown timer working for multiple data in mysql database. I have already made a successful countdown time function that only works with one data using the if statement in php, but when I try to do it with multiple data using the while statement in php it doesn't work.here is my php code
//TODAY'S DATE
$today = time();
//FETCHES DATE AND TIME FOR THE EVENT FROM DATABASE
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$title = $row['title'];
$cname = $row['cname'];
$team = $row['team'];
$description = $row['description'];
$endtime = $row['endtime'];
echo "<tr>";
echo "<td width='16%'><strong>Title:</strong></td>";
echo "<td width='16%'>$title</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Client name:</strong></td>";
echo "<td width='16%'>$cname</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Team:</strong></td>";
echo "<td width='16%'>$team</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Description:</strong></td>";
echo "<td width='16%'>$description</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>End time:</strong></td>";
echo "<td width='16%'>$endtime</td>";
echo "</tr><tr>";
echo"</BR>";
echo"</BR>";
}
$conn->close();
below is my javascript that suppose to run the count down
<script language="JavaScript">
var today = new Date();
var DD = today.getDate();
var MM = today.getMonth()+1; //January is 0!
var YYYY = today.getFullYear();
//let get the Difference in Sec btw the two dates
var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';
var ProgEndTime = new Date(_DateFromDBProgEndDate);
var TodayTime = new Date();
var differenceTravel = ProgEndTime.getTime()- TodayTime.getTime() ;
var seconds = Math.floor((differenceTravel) / (1000));
////////////////////////////////
var SecDiffFromToday = seconds;
var seconds = SecDiffFromToday;
function pad(n) {
// utility function to pad a number to 2 digits:
return ('0' + n).substr(-2);
}
function timer() {
var todaySeconds = Math.floor(new Date().getTime() / 1000);
// collect the html first in an array
var html = [];
// keep track whether there are still counters not yet zero:
var allDone = true;
// go through the list of dates:
endDatesInSeconds.forEach(function (endDateSeconds) {
var totalSeconds = endDateSeconds - todaySeconds;
var days = Math.floor(totalSeconds/24/60/60);
var seconds = Math.floor(totalSeconds - days*86400);
var hours = Math.floor(seconds/3600);
seconds = Math.floor(seconds - hours*3600);
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
// add a part of html
html.push(
totalSeconds <= 0
? 'project time Completed'
: days + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds));
// when at least one counter is not complete, we are not done:
allDone = allDone && totalSeconds <= 0;
});
// now put the html in the document:
document.getElementById('countdown').innerHTML = html.join('<br/>');
if (allDone) {
clearInterval(countdownTimer);
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
the javascript run the countdown by getting it value from the php (var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';)
I get the GMT time in PHP and I would like to make it count, like the clocks.
<?php $time = gmdate('H:i:s'); ?>
<script>var time = <?php echo($time) ?>;
setInterval(function() {
time += 1;
$("#timediv").text("Current time (GMT): " + time);
//somehow convert it to 11:44:31 AM ??
}, 1000);
</script>
Can seomeon help me?
First of all, relying on setTimeout/setInterval accuracy for displaying time is not a good idea. There are multiple reasons for them not being that accurate, like CPU slowdowns. That's why you should rather use Date object, which uses actual clock.
This is what I do when I want to use my server's time on the client side:
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<!-- dateFormat plugin for nice and easy time formatting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<script>
var clientTime = (new Date()).getTime(),
serverTime = <?php echo time() ?> * 1000,
difference = clientTime - serverTime;
setInterval(function () {
var now = new Date();
now.setTime(now.getTime() - difference);
$("#timediv").text("Current time (GMT): " + $.format.date(now, "hh:mm:ss a"));
}, 1000);
</script>
The key concept behind it is to calculate the difference between server time and client time. Then, you normalize your client side (created each time with new Date()) with the difference. We are still using setInterval, but even if it's delayed or accelerated for some reason, the time displayed is still correct.
I would not follow motanelu's answer but change it to this:
<script>var time = Date.parse('<?php echo($time) ?>');
setInterval(function() {
time.setSeconds(time.getSeconds() + 1);
$("#timediv").text("Current time (GMT): " + time);
//somehow convert it to 11:44:31 AM ??
}, 1000);
</script>
This creates a Date object which can you can format with for example time.toLocaleTimeString();
Replace
<?php $time = gmdate('H:i:s'); ?>
with
<?php $time = gmdate('h:i:s A'); ?>
Thank you guys, I made it:
PHP:
$time = gmdate('H:i:s');
$time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $time);
sscanf($time, "%d:%d:%d", $hours, $minutes, $seconds);
$timeInSeconds = $hours * 3600 + $minutes * 60 + $seconds;
Javascript:
<script>
function fromSeconds(sec){
var d=new Date(0,0,0);
d.setSeconds(+sec);
return (d.getHours() ? d.getHours()+":" : "")+d.getMinutes()+":"+d.getSeconds();
}
var time = <?php echo($timeInSeconds) ?>;
var newTime = 0;
setInterval(function() {
time += 1;
var newTime = fromSeconds(time);
$("#timediv").text("The current GMT time is: " + newTime);
}, 1000);');
?>
</script>
This question already has answers here:
javascript clock with server time [duplicate]
(4 answers)
Closed 8 years ago.
I struggling with server time. I need timer on my website (count every second) but not client side time but server. But my script operating only with client time:
<script>
setInterval(function() {
var d = new Date();
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
Script above work fine.
How I can integrate server time and update very one second?
Get the date from the server, convert it to a javascript date, then increment it yourself.
<?php $today = getdate(); ?>
<script>
var d = new Date(Date.UTC(<?php echo $today['year'].",".$today['mon'].",".$today['mday'].",".$today['hours'].",".$today['minutes'].",".$today['seconds']; ?>));
setInterval(function() {
d.setSeconds(d.getSeconds() + 1);
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
EDIT: JSFiddle with example PHP echoed in.
I worked on a code for count down using the server time . You can use something similar to this for your code
<?php
$now = date('d-m-Y');
$end= "01-01-2013"
$date = strtotime($end) - strtotime($now);
$days = date('d', $date);
$monthes= date('m', $date);
$years= date('Y', $date);
?>
<script>
var days = "<?= $days ?>";
var monthes= "<?= $monthes?>";
var years= "<?= $years?>";
document.getElementById('countdown').innerHTML = days+ ' days';
document.getElementById('countdown').innerHTML += monthes+ ' monthes';
document.getElementById('countdown').innerHTML += years+ ' years';
</script>
i have opencart module daily deal, but the countdown timer is not working.
function code:
<?php
class ModelCatalogSpecialPriceCountDown extends Model {
public function getProductSpecialDates($product_id) {
(string) $display_output = null;
(string) $minute = 60;
(string) $hour = 60 * $minute;
(string) $day = 24 * $hour;
if ($this->customer->isLogged()) {
$customer_group_id = $this->customer->getCustomerGroupId();
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$query = $this->db->query("SELECT date_start, date_end FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");
if ($query->num_rows) {
$time_left = strtotime($query->row["date_end"]) - strtotime(date('Y-m-d'));
$days_left = floor($time_left/$day);
if ($time_left > 0)
{
$display_output = getdate();
$display_output["days_left"] = $days_left;
}
}
return $display_output;
}
}
?>
and the code using it:
<!-- Countdown start -->
<div id="defaultCountdown<?php echo $product['product_id'];?>" class="countdown_dashboard"></div>
<script type="text/javascript"><!--
$(document).ready(function() {
$('#defaultCountdown<?php echo $product["product_id"]; ?>').countdown({
until: new Date(<?php echo $product['yleft'];?>, <?php echo $product['mleft'];?> - 1, <?php echo $product['dleft'];?>)
});
});
//-->
</script>
My countdown doesn't work, the numbers change only when I refresh the page.