You need to generate syntactically VALID javascript. PHP can send text in ANY part of the page that it generates, but this does not necessarily mean that it is actually USABLE text. In your case, you forgot ;
, so your generated javascript is actually a syntax error:
var num = <?php echo $number ?>; ^--- missing
The same thing happens when you output text. Consider where you store the username in a variable:
<?php $name = "Miles O'Brien"; <script> var name = <? php echo $name ?>; </script>
This WATCH OK, but it will generate another syntax error:
var name = Miles O'Brien;
there are no quotes around the entire line, and the inline quote will start the line in javascript, causing the JS interpreter to complain about the undefined variable "Miles", the undefined variable "O", and the string with an inexhaustible string.
Instead, PHP should have been:
var name = <? echo json_encode($name) ?>;
JSON encapsulation ensures that you insert syntactically valid Javascript values.
source share