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.
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.
json_encode to properly quote and escape the string from PHP. addslashes does the job most of the time, but who knows what kind of stuff is in that string? There could be newlines!json_encode on a string just returns that string formatted for use in Javascript code. Example: $str = 'This is an "example".'; echo json_encode($str); would print "This is an \"example\".";.script tag but I forgot to copy here.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
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).