Trekdrop
Trekdrop

Reputation: 495

PHP variable in JavaScript is not getting updated

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?

Upvotes: 0

Views: 410

Answers (1)

1321941
1321941

Reputation: 2180

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

Upvotes: 1

Related Questions