Using php value in jQuery script

How can I use the php value in jQuery ?, what I do is pull the watt rate out of the database using php as follows and save 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 a jQuery script that concatenates all the result lines and puts them in a range.

 <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 I'm not sure how to refer to the $ vatrate value declared in php in jQuery so that I can get the price + wat. VAT is a sales tax for those who are not in the UK :).

+4
source share
3 answers

On your PHP page in your javascript / jquery code, you can do something like this to assign a PHP variable to your javascript variable (NB you cannot do oppisite because PHP is the server side and javascript is the client side):

 <script> var vatrate = '<?php echo($vatrate);?>'; </script> 
+10
source

Just an echo of PHP where you want the value to be in a script ...

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

However, you should not rely too heavily on javascript without proper backups.

0
source

If you repeat the variable in Javascript, you can omit the quotation marks and use it as a float, which will mean that the Javascript variable is a floating point and will be ready to work for calculation. Casting as a float will also prevent any Cross Site Scripting (XSS) scripting.

 <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> 
0
source

Source: https://habr.com/ru/post/1489281/


All Articles