0

I'm trying to grab a session variable in my javascript, but have some problems getting it right.. I didn't get that to work, so instead i tried to store it in a hidden variable in HTML first, but i dont know how to store a session variable there.. Can anyone guide me to the right path?

The code (HTML file): ($_SESSION["price1"] is equal to "20.00")

<input type="hidden" id="price" value="$_SESSION["price"]"/>

The code in javascript:

    var sessionValue = document.getElementById("price").value;

What to do?

2
  • use price1 instead of price in your html Commented Oct 9, 2013 at 4:27
  • try document.getElementById("price").defaultValue Commented Oct 9, 2013 at 4:31

5 Answers 5

3

you missed PHP tags <?php and echo, change to:

<input type="hidden" id="price" value="<?php echo $_SESSION["price"]; ?>"/>
Sign up to request clarification or add additional context in comments.

Comments

2

What everyone bellow mentioned is perfectly true, inside HTML you can just wrap stuff in <?php echo $_SESSION['price']; ?> and it will work (notice the <?php tags)

However, the right way to do this -- considering you want to pass a PHP variable (in your case a session variable) to javascript is to directly insert it into a javascript variable instead of accessing the DOM. This way, you also have it instantly and don't have to wait for the DOM to be loaded

<script>
var price = '<?php echo $_SESSION["price"]; ?>';
alert('The price is: ' + price);
</script>

Comments

1

This line:

<input type="hidden" id="price" value="$_SESSION["price"]"/>

Should be:

<input type="hidden" id="price" value="<?php echo $_SESSION["price"];?>"/>

You are missing the php tags

Comments

1

change,

<input type="hidden" id="price" value="$_SESSION["price"]"/>

To,

<input type="hidden" id="price" value='<?php echo $_SESSION["price"]; ?>'/>

Comments

1

Grab your session variable in JavaScript using this:

var my_session_price = "<?php echo $_SESSION["price"]; ?>";

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.