4

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 :) .

3 Answers 3

11

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>
Sign up to request clarification or add additional context in comments.

2 Comments

To be clear, in a PHP page you can do this. JavaScript and jQuery does not allow you to do this by default. +1 though.
Thanks very much, simple fix ! :-)
0

Just echo the PHP where you want the value to reside in the script...

<?php $bar = "bar"; ?>
<script>
var foo = "<?php echo $bar; ?>";
alert(foo); // bar
</script>

However, you should never rely too heavily on javascript without the proper fallbacks.

Comments

0

If you echo the variable into Javascript, you can omit the the quotes and cast it as a float, which will mean the Javascript variable is a float, and will be ready to work with for the calculation. Casting as a float will also prevent any possibility of Cross Site Scripting (XSS).

<script>
var vatRate = <?php echo (float)$vatrate; ?>;

$(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);
        });

        // add the vat to the grandtotal
        // assuming vatRate is 20 for 20%, not 0.2
        grandtotal += (grandtotal * (vatRate / 100));
        $('#grandtotal').text(grandtotal);
    });
});
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.