Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am creating a PHP session using the following code:

<?php
     session_start();
     $_SESSION['loggedin'] = true;
?>

How can I access the variable loggedin in Javascript? In other words, I want to check in Javascript if the variable 'loggedin' is set or not.

share|improve this question
    
You could write $_SESSION['loggedin'] into a <script> block so that by the time it makes it to the client for JavaScript to evaluate, the variable will be written in... but if all you are trying to do is detect whether or not the user is logged in, why not have PHP output the page with some specific element or ID that you can detect via JavaScript easily? –  mattacular Aug 10 '11 at 19:03
add comment

2 Answers

up vote 4 down vote accepted

The only way to do this is to write the value into a script block on the page as a JS variable, and reference it that way, or to make an AJAX request to a page that then returns the logged in status. There's no way for your client to directly access the session state in any server language.

share|improve this answer
    
+1, a more fleshed-out version of my answer. –  Matt Ball Aug 10 '11 at 18:37
add comment

You can't — at least not directly.

PHP runs on the server, but JavaScript runs in the browser.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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