Herland Cid
Herland Cid

Reputation: 574

can't pass php session variable to javascript string variable

Can't pass php session variable to javascript string variable

While the $_SESSION['Id'] variable exists, the javascript can't seem to bring it at least with this syntax:

CODE

<?php session_start(); ?>

<script>
var a = "<?php echo $_SESSION['Id']; ?>";
alert(a);
</script>

Upvotes: 0

Views: 1148

Answers (3)

MonkeyZeus
MonkeyZeus

Reputation: 20747

Your syntax looks fine. What happens if you write this?

<?php
php session_start();

echo '<div style="padding:30px; background-color:#ffffff;"><pre>'.print_r($_SESSION, true).'</pre></div>';

?>

<script>
var a = "<?php echo $_SESSION['Id']; ?>";
alert(a);
</script>

If that doesn't work then try manually setting the ID before the echo

<?php
php session_start();

$_SESSION['Id'] = 'AN ID!!!';

echo '<div style="padding:30px; background-color:#ffffff;"><pre>'.print_r($_SESSION, true).'</pre></div>';

?>

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94682

Try this to see if the variable $_SESSION['Id'] exists and is set to something

<?php 
    session_start();

    print_r( $_SESSION );
?>

<script type="text/javascript">
  var a = "<?php echo $_SESSION['Id']; ?>";
  alert(a);
</script>

Upvotes: 1

Brian Phillips
Brian Phillips

Reputation: 4425

First, like the comments have mentioned, make sure you're using the correct case of id, whether it's id or Id.

Second, try using json_encode to convert it for javascript use. No need for "":

var a = <?php echo json_encode($_SESSION['Id']); ?>;

Upvotes: 1

Related Questions