my php code has a value of 2 digits like
$var1 = 16;
$var2 = 24;
$var3 = 31;
but when i used those value and put it in my javascript like for example
var var1 = <?php echo $var1; ?>
var var2 = <?php echo $var2; ?>
var var3 = <?php echo $var3; ?>
console.log(var1+"-"+var2+"-"+var3)
the output is **1-2-3**
instead of **16-24-31**
it only get the first digit i even put window.onload
function to make sure to load the php and html first before the script.
The problem is a result of two things:
?>
.This means that your JS code ends up being something like
var var1 = 16var var2 = 24var3 = 31
which is not what you expect (actually the above is a syntax error; if the code compiles in your case it might be a result of the example being not identical to the code that runs).
The proper solution is to terminate each statement with a semicolon:
var var1 = <?php echo $var1; ?>;
var var2 = <?php echo $var2; ?>;
var var3 = <?php echo $var3; ?>;
What would also work (although I recommend to avoid it) is to put some extra newlines after each assignment and let ASI take over:
var var1 = <?php echo $var1; ?>
var var2 = <?php echo $var2; ?>
var var3 = <?php echo $var3; ?>
As an aside, straight echo
of the variables works in this case because they are numeric. In general, the proper way to transfer variables to JS is through json_encode
:
var var1 = <?php echo json_encode($var1); ?>;
try this : It worked for me
<?php
$var1 = 16;
$var2 = 24;
$var3 = 31;
?>
<script>
var var1 = <?php echo $var1; ?>;
var var2 = <?php echo $var2; ?>;
var var3 = <?php echo $var3; ?>;
alert(var1+"-"+var2+"-"+var3);
console.log(var1+"-"+var2+"-"+var3);
</script>