0

I want to use $_SESSION['total'] in javascript so I can use it in a function.

What I have tried:

var total = '<%= Session["total"]%>'; Prints: <%= Session["total"]%>

var total = <?php $_SESSION['total']; ?>; Prints Uncaught SyntaxError: Unexpected token <

var total = "<?php $_SESSION[\'total\']; ?>"; Prints <?php $_SESSION[\'total\']; ?>

Is there a way of getting the session value and use it in javascript?

EDIT: Ok, if the you are trying this in an external javascript, it doesn't work, it work when you write the script in the php, well for me.

PPasf
  • 5
  • 2
  • The problems you're having indicate that the page isn't being executed by PHP. Does it have a `.php` extension? Are you accessing it from a webserver? – Barmar Oct 13 '16 at 08:00
  • @Barmar the javascript is an external javascript – PPasf Oct 13 '16 at 08:23
  • You need to put it in a `.php` file so that the server will process it with PHP. Or configure the webserver so that it processes `.js` files with PHP. – Barmar Oct 13 '16 at 08:27

1 Answers1

4

The second one should be fine, but you must also put echo before the session:

var total = <?php echo $_SESSION["total"]; ?>;
L. Herrera
  • 490
  • 4
  • 13
  • 1
    When the complete page gets rendered in the server side, php runtime translates `` into actual session value. That's the concept behind it. so, the javascript variable `total` will have the actual value getting set into it – Keerthivasan Oct 13 '16 at 08:07
  • 1
    @Keerthivasan The problem he's having is that the file isn't being rendered by PHP. He apparently tried putting PHP code inside a `.js` file. – Barmar Oct 13 '16 at 08:29