Ruther Melchor
Ruther Melchor

Reputation: 69

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.

Code:

echo "<script type=text/javascript>";
echo "var hidden = false;";

echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';"; 
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";

echo "}";
echo "}";
echo "</script>";

How can I make the script to properly retrieve the data inside $_SESSION["username"];?

Upvotes: 0

Views: 1340

Answers (3)

Jack Sun
Jack Sun

Reputation: 287

Did you start session in this page?If you didn't,use the follow code to start session.

    session_start();

Then change your code to

echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n";  //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n"; 
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";

it will be ok.

Upvotes: 0

coderMe
coderMe

Reputation: 2169

As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:

echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";

However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.

?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
  if(!hidden) {
      document.getElementById('clickdb1').style.visibility = 'hidden';
      document.getElementById('db1').style.visibility = 'visible'; 
      document.getElementById('db1').disabled = false;
      document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
    }
}
</script>;
<?php

Upvotes: 0

Havenard
Havenard

Reputation: 27874

Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:

document.getElementById('db1').value = John;

But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).

Upvotes: 2

Related Questions