The problem is a result of two things:
- You are not ending your JS statements with semicolons.
- PHP eats up one newline character if it follows the closing tag
?>
.
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); ?>;