Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Php value in jQuery script

how would I go about using a php value in jQuery ?, what I am doing is pulling the vat rate from the database using php as follows and storing in $vatrate :

$sqlv = <<<SQL
SELECT *
FROM   `vatrate`
WHERE  id='1'
SQL;
if(!$resultv = $db->query($sqlv)){
  die('There was an error running the query [' . $db->error . ']');
}
while($rowv = $resultv->fetch_assoc()){
    $vatrate =  $rowv['vatrate'];
} ?>

Then I have my jQuery script that adds all of the line totals together and puts it into a span.

<script>
$(document).ready(function() {
    $('input').on('keyup', function() {
        var rawValue, grandtotal = 0;
        $('span[id^="linetotal"]').each(function(i, elem) {
            rawValue = $.trim($(this).text());
            if (rawValue == '') rawValue = 0;
            grandtotal += parseFloat(rawValue);
        });
        $('#grandtotal').text(grandtotal);
    });
});
</script>

But now im not sure how to reference the $vatrate value declared in php in jQuery, so that I can get the price + vat. VAT is sales tax for anyone not in the Uk :) .

like image 947
Iain Simpson Avatar asked Dec 21 '22 03:12

Iain Simpson


1 Answers

In your PHP page into your javascript/jquery code you can do somenting like this to assign a PHP variable to your javascript variable (N.B. you can't do the oppisite because PHP is server side and javascript is client side):

<script>
    var vatrate = '<?php echo($vatrate);?>';
</script>
like image 53
Alessandro Minoccheri Avatar answered Jan 19 '23 00:01

Alessandro Minoccheri