I'm trying to pass a PHP variable (number) to JavaScript. It kind of works but as soon as the number changes, it's not getting updated. My code:
$totalamount = $woocommerce->cart->get_total();
$totalamount = preg_replace("/[^0-9\.]/", "", $totalamount);
$totalamount = number_format($totalamount, 2, '.', '');
var_dump($totalamount);
?>
<script type="text/javascript">
var Amount = "<?php echo $totalamount; ?>"
In the var_dump($totalamount); the number get's updated every time. In JavaScript it gives 0 after a change.
What is the proper way to pass a variable to JavaScript so it gets updated?
-
3Unless you reload the page or use AJAX, your variable will only update the first time.j08691– j086912013年09月24日 12:11:32 +00:00Commented Sep 24, 2013 at 12:11
-
How do you change the number?Shimon Rachlenko– Shimon Rachlenko2013年09月24日 12:14:43 +00:00Commented Sep 24, 2013 at 12:14
-
1Can you be a bit more clear about what your expecting to happen? The number in $totalamount will be generated when the page loads and outputted to the javascript. Or are you saying that on the page load, the var_dump outputs the correct number but the echo totalamount doesn't?Matthew– Matthew2013年09月24日 12:17:41 +00:00Commented Sep 24, 2013 at 12:17
1 Answer 1
PHP is a server side language which means it is only executed at the time the page is loading, and the code will not be re-run unless you refresh the page.
To get around this you can retrive the total using an AJAX call which would get the total in the background and then update the page.
To get started with Ajax here is a good tutorial: Ajax
7 Comments
document.write("<input type=\"hidden\" NAME=\"amount\" value=\"" + Amount + "\" />"); It's not in the same file.Explore related questions
See similar questions with these tags.