0

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.

2
  • 1
    Look at the resulting JavaScript code and you will see what the problem is. Commented Feb 6, 2012 at 19:55
  • This question is similar to: How to incorporate a PHP-generated value into JavaScript code on the page?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 28, 2024 at 13:32

2 Answers 2

4

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'); ?>;
Sign up to request clarification or add additional context in comments.

4 Comments

I've just tried both of these and in both cases the alert box displays "<?php echo('test'); ?>" instead of just test.
Sounds like PHP isn't enabled on your server, or that your file isn't named with a .php extension.
yep, it was in a .js file. Changed the extension to .php and it works now. Thanks.
No problem. Why were you using <script> tags in a .js file, though?
1

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 ( "" )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.