# Trying to send a session variable to javascript

**URL:** <https://forum.kirupa.com/t/trying-to-send-a-session-variable-to-javascript/327464>\
**Category:** programming\
**Created:** [March 2, 2012, 2:28pm UTC](https://forum.kirupa.com/t/trying-to-send-a-session-variable-to-javascript/327464 "2012-03-02T14:28:38Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![andrewlong](https://avatars.discourse-cdn.com/v4/letter/a/f07891/32.png) [@andrewlong](https://forum.kirupa.com/u/andrewlong)\
**Post date:** [March 2, 2012, 2:28pm UTC](https://forum.kirupa.com/t/trying-to-send-a-session-variable-to-javascript/327464/1 "2012-03-02T14:28:38Z")

</div>

Ideally, I would like to send a session variable to javascript. I figured I would do something like this:

```auto

echo("<script type='text/javascript'>var id=".$_SESSION['id'].";alert(id);</script>";

```

On the page the php script generates I get the source exactly as expected

```auto

<script type='text/javascript'>var id=1234567890;alert(id);</script>

```

But it never alerts. If I try to access id in other ways, I get undefined. It’s like this if I put it in the head or the body. If I declare a variable without injecting a PHP variable into it, it works fine (e.g. if after I declar id I also put var a=1;alert(a); it will alert fine, or I can access the variable fine).

To my novice understanding of PHP, I thought it just generates a string and sends it to your computer for the browser to interpret. So how can a browser receive that string and know that some value was declared using a php variable and that isn’t allowed?
