Reputation: 2087
How do I make this work? I've googled and even saw some examples here on Stackoverflow which show this kind of coding, but it doesn't work for me.
<script type="text/javascript">
var infoClass = "";
infoClass = <?php echo('test'); ?>;
alert(infoClass);
</script>
The alert box displays empty box.
Upvotes: 0
Views: 132
Reputation: 11285
Make sure your code is in a .php file, or inside a file that has an extension that will be parsed by PHP.
Also make sure the printed content will be inside of a string ( "" )
Upvotes: 1
Reputation: 179994
Your resulting JS code will be:
infoClass = test;
As there's no variable test
, this won't work right. You need to wrap it in quotes, just like any other string:
<script type="text/javascript">
var infoClass = "";
infoClass = '<?php echo('test'); ?>';
alert(infoClass);
</script>
You can also use json_encode()
, which may be handy for more complicated situations where you're echoing out arrays, objects, etc.:
infoClass = <?php echo json_encode('test'); ?>;
Upvotes: 4