function myfunc() { alert...">

How to embed a snippet of PHP code in javascript

my code

<?php session_start(); $_SESSION['errors']="failed"; ?> <head> function myfunc() { alert(<?php echo $_SESSION['errors']; ?>); } </head> <body onload="myfunc();"> 

but msg warning does not appear.

+4
source share
4 answers

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.

+7
source

PHP just prints failed , it won’t print line separators with it, so make sure you put them in:

 function myfunc() { alert("<?php echo $_SESSION['errors']; ?>"); } 
+2
source

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]
+2
source

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).

+1
source

Source: https://habr.com/ru/post/1310207/


All Articles