I am trying to print a variable value within the javascript function. If the variable is an integer ($myInteger) it works fine, but when I want to access text ($myText) it gives an error.
<?php $myText = 'some text';
$myInteger = '220';
?>
<script type="text/javascript">
<?php print("var myInteger = " . $myInteger . " ;\n");?> //works fine
<?php print("var myText = " . $myText . " ;\n");?> //doens't work
</script>
Can anyone explain to me why this happens and how to change it?
The problem with your code from the question is that the generated Javascript code will be missing quotes around the string.
You could add quotes to the output manually, as follows:
However, note that this will break if the string itself contains quotes (or new-line characters, or a few others), so you need to escape it.
This can be dealt with using the
addslashes()function, among others, but this may still have issues.A better approach would be to use PHP’s built-in JSON functionality, which is designed specifically for generating Javascript variables, so it will do all the escaping for you correctly.
The function you’re looking for is
json_encode(). You’d use it as follows:This will work with any variable type — integer, string, or even an array.
Hope that helps.