I need some data from SQL to Javascript, so I called them in PhP and I'm trying to pass these values to Javascript, but the code below causes a NaN failure... if I set a PhP command for the Javascript variable, I can't use it as a numeric value...
<?php
$val=12;
?>
<script>
var val="<?php echo $val; ?>";
</script>
I got a solution but I'm sure, this is not the best way to do this:
<?php
$val=12;
?>
<input type="number" id="val" name="val" value="<?php echo $val; ?>" hidden>
<script>
var val=getElementById('val').value;
</script>
One way of doing it is removing the quotes:
But there may be edge cases in which php yields unexpected results, so in my opinion it's a good practice to keep the quotes and to update the value.
If you are sure that the value will always be an integer and/or that you need an integer in your code you can do:
Or if you are using lodash:
Remember to pass 10 as the second parameter which will specify the radix in the first case, as there may be edge cases in which numbers are interpreted with a base different than 10 (like hexadecimal or binary).
Otherwise if the value can be a float I suggest to do:
And if you want to limit the digits after the decimal point you can do:
.toFixed()
returns a string so if you still need a number it's better to convert it back to a number with theNumber()
function.Passing the value through an input may work but it doesn't look like a good practice, anyway to get the element you will need to add
document
beforegetElementById
: