How to put php inside JavaScript?
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:
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.
You're missing quotes around your string:
...
var htmlString="<?php echo $htmlString; ?>";
...
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>
The only proper way to put server side data into generated javascript code:
<?php $jsString= 'testing'; ?>
<html>
<body>
<script type="text/javascript">
var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
alert(jsStringFromPhp);
</script>
</body>
</html>
With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...
For similar reasons I recommend to use document.createTextNode()
instead of setting the innerHTML
. Ofc. it is slower, but more secure...
you need quotes around the string in javascript
var htmlString="<?php echo $htmlString; ?>";