0

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>
3
  • 1
    What do you get when you var_dump $_SESSION? Commented Aug 29, 2013 at 20:20
  • Can you post your Javascript code? We need to see how you're trying to acquire that value. Commented Aug 29, 2013 at 20:21
  • 2
    PHP array indexes are case sensitive. Should Id be lowercase as id? Commented Aug 29, 2013 at 20:22

3 Answers 3

2

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>';

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

Comments

1

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

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.