5

I need to write some PHP code inside a Javascript's "document.write()". This is a dummy example, but in the future Javascript will generate automatically that PHP code.

This is the Hello World I have coded:

MyFile.php

<html>
<body>
<script type="text/javascript">
document.write("<?php echo \"Hello World\"; ?>");
</script>
</body>
</html>

However, nothing is displayed, and in the DOM file I get this:

<html>
<body>
<script type="text/javascript">
<!--?php echo  "Hello World"; ?-->
</script>
</body>
</html>

Any help? Thanks

5
  • 3
    "JavaScript will generate automatically that PHP code". PHP is server-side, JavaScript is client-side. You can't do that. Commented Aug 13, 2012 at 16:57
  • 3
    mixing PHP and JS code - just don't do it! Commented Aug 13, 2012 at 16:58
  • 1
    <?php echo "document.write(\"Hello World\");" ?> generating javascript from PHP Commented Aug 13, 2012 at 16:58
  • 1
    What is the larger aim you are trying to accomplish? Commented Aug 13, 2012 at 17:04
  • @RocketHazmat Yes you are write. No one can do it. If he want to call to a php script. Then he can do AJAX Call to that php page and return it. Commented Apr 28, 2014 at 8:56

5 Answers 5

8

The PHP gets evaluated before the JavaScript, so no need to escape the quotes.

document.write("<?php echo "Hello World"; ?>");
Sign up to request clarification or add additional context in comments.

Comments

3

when javascript runs that means the response is showing to the browser not compiling the php code any more so as you are putting php code in javascript that means you want something from server than no other alternate but ajax.

Comments

2

It's impossible. Php need server-side to runs, and javascript runs just on client side. What you can do is prepare one php code to write one file and call this code by javascript.

Comments

2

What you ask is not possible. Javascript generates the php code client side, after the server is finished. The server never sees the PHP code.

Comments

0

If you need to execute some PHP code via javascript, you would need to have the PHP housed on a server somewhere where it can be run (i.e. the browser client will not run it) and then you need to used AJAX to run that script and do whatever you need to do with its output.

Comments

Your Answer

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