0

Possible Duplicate:
Passing PHP variable into JavaScript

I want to obtain a PHP variable, to use it in an if-condition in JavaScript.

I was trying to use it like this:

var phpLogin = <?php $_SESSION['login'] ?>;

But it's wrong in syntax terms. So, how can I use a PHP variable in JavaScript?

2
  • 2
    var phpLogin = <?php ECHO $_SESSION['login'] ?>; You forgot to echo varible. And check if key exists in $_SESSION before echo... Commented Nov 26, 2011 at 17:27
  • and possible more in stackoverflow.com/… Commented Nov 26, 2011 at 17:42

5 Answers 5

3

Use json_encode and don't forget echo.

var phpLogin = <?php echo json_encode($_SESSION['login']) ?>;
Sign up to request clarification or add additional context in comments.

8 Comments

No semi colon in the php code?
@Tim It's not necessary in this case.
OP also did not indicate that the returned data was desired to be in JSON format
You dont need one because it only contains a single statement and then closes out of php... but you can add it in if you like.
@Tim So? He has to use JSON, otherwise it'll only work if $_SESSION['login'] is a number.
|
2

You forgot the echo.

<?php echo $_SESSION['login']; ?>

or just

<?=$_SESSION['login']?>

1 Comment

No semi colon terminating the PHP code in the 2nd example
2

The problem in your code is that you forgot the echo:

var phpLogin = <?php echo $_SESSION['login'] ?>;

Comments

1

Try: var phpLogin = "<?php =$_SESSION['login']; ?>";

1 Comment

I tried, but, unfortunately, it returns it as a string. Like: "<?php =$_SESSION['login']; ?>", instead of a php variable.
1

It may look like overkill, but for safety reasons you should use json_encode when echo'ing directly to PHP:

var phpLogin = <?=json_encode($_SESSION['login'])?>;

Or, in its longer form:

var phpLogin = <?php echo json_encode($_SESSION['login']); ?>;

Or, to also accept empty sessions:

var phpLogin = <?php echo @json_encode($_SESSION['login']); ?>;

This will simply output NULL when there's no login session.

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.