1

I am using the following code in a seperate js file to use a php $_SESSION variable. However, I am getting a syntax error of SyntaxError: missing ; before statement. I have tried putting the ; in the usual place, but still the same.

What is the correct way to use a php session in js file. Thanks

var companycode = '<?php echo $_SESSION['ls_idcode_usr']?>';
user1532468
  • 1,723
  • 8
  • 41
  • 80
  • You want to use PHP code in `.js` file or want to send PHP code as an Ajax request and compile it in `.php` file? If the second one is your case, check this: https://stackoverflow.com/questions/3241422/include-php-inside-javascript-js-files – ata Feb 24 '18 at 07:42
  • 1
    maybe escape single quote – Dhaval Feb 24 '18 at 07:43

2 Answers2

1

There may be special characters in the value of the session variable. Use json_encode() to output a valid Javascript literal:

var companycode = <?php echo json_encode($_SESSION['ls_idcode_usr']);?>;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • That gives me error of: `SyntaxError: expected expression, got '<'`. Thanks – user1532468 Feb 24 '18 at 07:54
  • Sorry, not understanding your comment. It is in php statement. I need to use in js file. Thanks – user1532468 Feb 24 '18 at 07:58
  • The JS statement has to be in a PHP script. Then PHP will execute the statement when it's creating the JS file. If you're not creating the JS file with PHP, you need to use AJAX to get values from the server. – Barmar Feb 24 '18 at 07:59
  • See https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – Barmar Feb 24 '18 at 08:00
  • Can you not use a php $_SESSION in js? The session is already generated just need to use in js. Thanks – user1532468 Feb 24 '18 at 08:03
  • PHP runs on the server, JS runs on the client. – Barmar Feb 24 '18 at 14:20
0

You can only use PHP in files ending in .php, otherwise the web server won't parse them looking for code to execute, and it'll just get passed down to the client.

You can certainly make a whatever.js.php file, where PHP will be involved in the production of the Javascript file that is passed down to the browser.

sorak
  • 2,607
  • 2
  • 16
  • 24