Reputation: 21
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>
Upvotes: 0
Views: 392
Reputation: 21
Thank you all! It's easier, then I thought! I thought, quotes are always needed, as JavaScript identify "<?php" tag as string.
Upvotes: 0
Reputation: 2059
One way of doing it is removing the quotes:
<script>
var val = <?php echo $val; ?>;
</script>
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:
var numericValue = parseInt(val, 10);
Or if you are using lodash:
var numericValue = _.parseInt(val);
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:
var numericValue = parseFloat(val);
And if you want to limit the digits after the decimal point you can do:
var numericValue = Number(parseFloat(val).toFixed(4));
.toFixed()
returns a string so if you still need a number it's better to convert it back to a number with the Number()
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
before getElementById
:
var val = document.getElementById('val').value;
Upvotes: 0