How to put php inside JavaScript?
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.
All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:
<html>
<head>
<script>
function myFunction(){
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>
You're missing quotes around your string:
...
var htmlString="<?php echo $htmlString; ?>";
...