I've tried (but its not working):
<?php $htmlString= 'testing'; ?> <html> <body> <script type="text/javascript"> var htmlString=<?php echo $htmlString; ?>; alert(htmlString); </script> </body> </html>
Here is the tutorial that I've used for that purpose:
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You can't. PHP is executed server side, and the finished content is sent to the browser. Javascript just sees the end result. All you can do is make an AJAX call and get the results from that.
Just write your php code in the javascript function or I'm the parameters. You can use PHP inside script tag too not a problem.
Try this:
<?php $htmlString= 'testing'; ?> <html> <body> <script type="text/javascript"> // notice the quotes around the ?php tag var htmlString="<?php echo $htmlString; ?>"; alert(htmlString); </script> </body> </html>
When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.
Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing'
to $htmlString
. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With