Reputation: 9679
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
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
Upvotes: 2
Reputation: 382841
Two errors in your code:
<script>
tagsTry 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
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
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