Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
2  
var phpLogin = <?php ECHO $_SESSION['login'] ?>; You forgot to echo varible. And check if key exists in $_SESSION before echo... – Glavić Nov 26 '11 at 17:27
and possible more in stackoverflow.com/… – Gordon Nov 26 '11 at 17:42

marked as duplicate by Gordon, mario, Rob W, Esailija, Justin Ethier Nov 26 '11 at 18:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

Use json_encode and don't forget echo.

var phpLogin = <?php echo json_encode($_SESSION['login']) ?>;
share|improve this answer
No semi colon in the php code? – Tim Nov 26 '11 at 17:28
@Tim It's not necessary in this case. – Artefacto Nov 26 '11 at 17:29
OP also did not indicate that the returned data was desired to be in JSON format – Tim Nov 26 '11 at 17:30
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. – prodigitalson Nov 26 '11 at 17:30
@Tim So? He has to use JSON, otherwise it'll only work if $_SESSION['login'] is a number. – Artefacto Nov 26 '11 at 17:31
show 3 more comments

You forgot the echo.

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

or just

<?=$_SESSION['login']?>
share|improve this answer
No semi colon terminating the PHP code in the 2nd example – Tim Nov 26 '11 at 17:29
1  
Avoid using short tags. – dlondero Nov 26 '11 at 17:31

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

var phpLogin = <?php echo $_SESSION['login'] ?>;
share|improve this answer

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

share|improve this answer
I tried, but, unfortunately, it returns it as a string. Like: "<?php =$_SESSION['login']; ?>", instead of a php variable. – Vitor Santos Nov 26 '11 at 18:12

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.