How to embed a snippet of PHP code in javascript
Two errors in your code:
- You are missing
<script>tags - You are missing single / double quotes in the alert
Try the following:
<?php session_start(); $_SESSION['errors']="failed"; ?> <head> <script> function myfunc() { alert('<?php echo $_SESSION["errors"]; ?>'); } </script> </head> You might want to put the myfunc() event in window.load or some kind of click event to test it. In addition, as ThiefMaster correctly suggested, you can use the addslashes function for $_SESSION["errors"] in alert .
Note. It is assumed that the file extension is for your php code.
It is actually not possible to insert a piece of PHP code in javascript. Because it is a meaningless JS engine that PHP does not understand.
You can generate all javascript using PHP.
So, to ask such a question, you must provide
- The exact javascript code you want to get.
- sample input
- and the result of executing your own code compared to [1]
Also, you have to make sure your php output doesn't contain anything that breaks the javascript line:
function myfunc() { alert('<?php echo addcslashes($_SESSION['errors'], "'/\\"); ?>'); } Note that I also remove the slash to ensure that </script> does not end the script tag (there is no other good way than escape-slash to prevent this).