How to pass numeric values from PhP to Javascript without posting data?

361 Views Asked by At

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>
2

There are 2 best solutions below

0
On

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;
0
On

Thank you all! It's easier, then I thought! I thought, quotes are always needed, as JavaScript identify "<?php" tag as string.