Reputation: 23
I'm trying to pass a php variable to javascript, but it doesn't seem to be working. I know that it works with just the javascript, just that it doesn't work when I'm trying to pass it with PHP. What am I doing wrong?
<?php
$sayIt = "Hello";
echo "
<script type = 'text/javascript'>
var msg = new SpeechSynthesisUtterance($sayIt);
window.speechSynthesis.speak(msg);
</script>
";
?>
Upvotes: 0
Views: 207
Reputation: 31
It doesn't work because the PHP will interpret the code like this:
<script type = 'text/javascript'>
var msg = new SpeechSynthesisUtterance(Hello);
window.speechSynthesis.speak(msg);
</script>
Then JavaScript will consider the Hello as a variable, which may not defined in JavaScript, you may should write it like this:
echo "<script type = 'text/javascript'>
var msg = new SpeechSynthesisUtterance(\"$sayIt\");
window.speechSynthesis.speak(msg);
";
Then it will be interpreted to this:
<script type = 'text/javascript'>
var msg = new SpeechSynthesisUtterance("Hello");
window.speechSynthesis.speak(msg);
</script>
Hope it will help you!
Upvotes: 3