4

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.

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

If on a PHP version that supports it, I would suggest using 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!
@Aistina: agreed but only oop knows whether he will be expecting json format and thereby use json_decode but his session data seems to be pure scalar string.
Using 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\".";.
actually it was inside script tag but I forgot to copy here.
2

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']; ?>");
}

Comments

2

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]

1 Comment

A harsh, but accurate statement.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.