nectar
nectar

Reputation: 9679

how to insert PHP code snippet in javascript

my code-

<?php
session_start();
$_SESSION['errors']="failed";
?>


<head>

    function myfunc()
    {        
         alert(<?php echo $_SESSION['errors']; ?>);
    }
</head>

<body onload="myfunc();">

but alert msg is not popping up.

Upvotes: 4

Views: 7186

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157941

As a matter of fact, it's impossible to insert PHP code snippet in javascript. Because it's nonsense JS engine don't understand PHP.
You can only generate whole javascript using PHP.

So, to ask such a question, you must provide

  1. an exact javascript code you want to get.
  2. an example of input data
  3. and a result of your own code execution, compared to [1]

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382841

Two errors in your code:

  • You are missing <script> tags
  • You are missing single/double quotes in alert

Try this:

<?php
session_start();
$_SESSION['errors']="failed";
?>


<head>

<script>
    function myfunc()
    {        
         alert('<?php echo $_SESSION["errors"]; ?>');
    }
</script>
</head>

You might want to put the myfunc() in window.load event or some click event to test it. Additionally, as rightly suggested by ThiefMaster, you may want to use the addslashes function for the $_SESSION["errors"] in the alert.

Note: It is assumed that file extension for your code is php.

Upvotes: 7

ThiefMaster
ThiefMaster

Reputation: 318688

Additionally you should ensure that your php output doesn't contain anything breaking the javascript string:

function myfunc()
{        
     alert('<?php echo addcslashes($_SESSION['errors'], "'/\\"); ?>');
}

Note that I also escape the forward slash to ensure that </script> doesn't end the script tag (there is no other good way except escaping forward slashes to prevent that).

Upvotes: 1

Andy E
Andy E

Reputation: 344713

PHP will just print out failed, it won't print out the string delimiters along with it, so make sure you put them in:

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

Upvotes: 2

Related Questions