Php Counter Hides Comma after loading and not showing permanently - javascript

I am trying to figure out a php counter. I have added Number format in a php function to print counter digits separated with a comma after first 3 digits. But Comma doesn't show up permanently after page load, When I reload the page, Comma shows for a moment but immediately hides. Below is the code i have used to get this result and please review the counter page.
<?php
$bg = get_field('counter_bg');
$init_value = get_field('init_value');
$init_date = get_field('init_date');
$seconds = strtotime("now") - strtotime($init_date);
$countup_value = get_field('countup_value');
$number = round((($seconds * $countup_value) + $init_value) * 100) / 100;
if($number) :
$title = get_field('counter_title');
$text = get_field('counter_text');
?>
<section class="home-section" id="home-counter" <?php if($bg['url']) echo "style='background-image: url({$bg['sizes']['slide-thumb']})'"; ?>>
<div class="container">
<?php
if($title) echo "<h3 class='counter-title'>{$title}</h3>";
echo "<div id='counter-number'>";
echo Number_format ($number);
echo "</div>";
if($text) echo "<div class='counter-text'>{$text}</div>";
?>
</div><!--containr-->
</section><!--home-section-->
<script>
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(<?= $countup_value ?>);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment('<?= $init_date ?>').format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2)
}
});
})(jQuery);
</script>
<?php endif; ?>
Please check the current Comman display issue at: http://airlite.designase.com/it/

According to the php number_format, you want to group the number by thousands. You can to that by changing the return of the calculate_value function like this:
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
The regex will add a comma every 3 digits, like this:
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(1);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment(20111031).format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="counter-number"></span>

Now it should keep the comma. You can set the number of decimals by changing the (2) parameter in toFixed() function in the end of the JS function.
<?php
$bg = get_field('counter_bg');
$init_value = get_field('init_value');
$init_date = get_field('init_date');
$seconds = strtotime("now") - strtotime($init_date);
$countup_value = get_field('countup_value');
$number = round((($seconds * $countup_value) + $init_value) * 100) / 100;
if($number) :
$title = get_field('counter_title');
$text = get_field('counter_text');
?>
<section class="home-section" id="home-counter" <?php if($bg['url']) echo "style='background-image: url({$bg['sizes']['slide-thumb']})'"; ?>>
<div class="container">
<?php
if($title) echo "<h3 class='counter-title'>{$title}</h3>";
echo "<div id='counter-number'>";
echo Number_format ($number);
echo "</div>";
if($text) echo "<div class='counter-text'>{$text}</div>";
?>
</div><!--containr-->
</section><!--home-section-->
<script>
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(<?= $countup_value ?>);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment('<?= $init_date ?>').format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2).replace(".", ",")
}
});
})(jQuery);
</script>
<?php endif; ?>

Related

Call PHP function inside JavaScript inside echo

I have read the other similar questions, but not found the answer, so here it is:
<?php
function load($page) {
echo "page: ".$page;
}
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '<?php load(page); ?>'
}
})
</script>
";
?>
The problem is that <?php load(page); ?> is not executed. If I write load(page); outside the echo, it works. Can anyone help me ?
Change the function to return:
function load($page) {
return "page: ".$page;
}
You're executing PHP with the echo so just use the return of load():
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '" . load($page) . "'
}
})
</script>
";

get current value input field quantity Woocommerce

there is any way in php to get the current value of quantity input of Woocommerce ?
I mean this field :
I need to get in this case 10 and output it.
How can I do that please?
Thanks
I resolve install this plugin : https://it.wordpress.org/plugins/woo-min-max-quantity-limit/
with this I can get the min and max value for each product.
I use the code inside :
$max = get_post_meta($product->id, '_wc_mmax_max', true);
$min = get_post_meta($product->id, '_wc_mmax_min', true);
the full code is :
// we are going to hook this on priority 31, so that it would display below add to cart button.
add_action('woocommerce_single_product_summary', 'woocommerce_total_product_price', 31);
function woocommerce_total_product_price() {
global $woocommerce, $product;
$max = get_post_meta($product->id, '_wc_mmax_max', true);
$min = get_post_meta($product->id, '_wc_mmax_min', true);
echo sprintf('<div id="product_total_price" style="margin-bottom:20px;display:none">%s %s</div>', __('Prezzo Prodotto :', 'woocommerce'), '<span class="price">' . $product->get_price() . '</span>');
echo sprintf('<div id="cart_total_price" style="margin-bottom:20px;display:none">%s %s</div>', __('Totale Carrello :', 'woocommerce'), '<span class="price">' . $product->get_price() . '</span>');
$moltiplicazione_prodotto = $product->get_price() * $max;
$moltiplicazione_prodotto = number_format($moltiplicazione_prodotto, 2, '.', '');
echo sprintf('<div id="prodotti_quantity" style="margin-bottom:20px;">%s %s</div>', __('Prezzo Prodotto :', 'woocommerce'), '<span class="price">' . get_woocommerce_currency_symbol() . $moltiplicazione_prodotto . '</span>');
?>
<script>
jQuery(function ($) {
var price = <?php echo $product->get_price(); ?>,
current_cart_total = <?php echo $woocommerce->cart->cart_contents_total; ?>,
currency = '<?php echo get_woocommerce_currency_symbol(); ?>';
var quantita_iniziale = $('[name=quantity]').val();
$('#prodotti_quantity').html(this.value);
console.log("quantita iniziale", this.value);
$('[name=quantity]').change(function () {
if (!(this.value < 1)) {
var product_total = parseFloat(price * this.value),
cart_total = parseFloat(product_total + current_cart_total);
$('#product_total_price .price').html(currency + product_total.toFixed(2));
$('#cart_total_price .price').html(currency + cart_total.toFixed(2));
if(this.value){
$('#prodotti_quantity').html(this.value).hide();
}
}
$('#product_total_price,#cart_total_price').toggle(!(this.value <= 1));
});
});
</script>
<?php
}

How to add var javascript value into id name?

How to add var javascript value into id name ?
I have $i = 5; and var i = 2;
How to concatenate php var $i with javascript var i ?
I tried like this but not work.
$('#test<?PHP echo $i; ?>'+i).live('click', function() {
do something
});
and
$('#test<?PHP echo $i; ?>'+i+'').live('click', function() {
do something
});
How can i do that ?
var phpi = '<?PHP echo $i; ?>';
$('#test' + phpi + i).live('click', function() {
//do something
});
or if you want PHP $i + JS i for exmaple (3 + 2 = 5)
var phpi = <?PHP echo $i; ?>; // no quotes here as we need number
$('#test' + (phpi + i)).live('click', function() {
//do something
});
PHP echo makes some space so that might hamper the selector use it like this

Multiple Countdown using PHP and Javascript

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

Javascript countdown only when page reload

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.

Categories

Resources