1

I have a login area of my site, and on login I set a session variable $_SESSION['logged_in'] = true.

Now I also have lots of forms and things where users can input comments. Obviously in my PHP validation I check the user is logged in simply using the session variable, but I want javascript validation too because I can make the user experience slicker that way.

$("body").on("click", ".submit", function(e){
    e.preventDefault();
    if (user == logged in){
        ...AJAX call to php file....
    }
})

So how do people generally do the bit where I check the user is logged in using javascript? ie if user == logged in

Lars
  • 7,908
  • 11
  • 52
  • 70
  • 1
    First I will mention that you should validate on the backend too. But, to answer the question, you can inject php variables into js... so if you have `$loggedIn = true`, you can do this is js: `if ()` – Jeff Shaver Mar 28 '13 at 10:31
  • Is this "the" way people do it? It does get the job done, but I somehow don't really like the mix of javascript and php. – Lars Mar 28 '13 at 10:34

1 Answers1

1
  • You can of course check user permissions by AJAX (with JSON for example), but this will provide some additional latency.

  • You can just write a value to global JS scope like this:

    if ( userIsLogged() ) { echo "<script>document.mysite.userlogged = true;</script>"; }

    then you can check document.mysite.userlogged variable.

  • You can also set a cookie in PHP, wich can be obtained in JavaScript. To get cookies properly in JS see that: Javascript getCookie functions

  • If you don't want to inject JS code, you can set some attribute like:

    <div id="comments" data-logged="<?php echo $isLogged; ?>"> ... </div>

    And get it by jQuery:

    if ( $("#comments").attr('data-logged') == 1 ) {

  • you can provide logged/notlogged specific functionality for the whole page by generating JS file, like: <script type="text/javascript" src="http://yoursite.com/somefile.php"> and generate it in php dynamically, but be aware of caching !

Personally i would go to data-XXX attribute if tou want to personalize single block, and global JS variable if you check logged condition many times in JS.

Community
  • 1
  • 1
Piotr Müller
  • 5,323
  • 5
  • 55
  • 82
  • Thanks this looks great. Can I ask why you might call the variable {document.mysite.userlogged} instead of just {userlogged}? – Lars Mar 28 '13 at 10:50
  • userlogged can be fine, but be aware of javascript scopes and closures, document.... cleanly signs that we think about global variable. Also if you want to set `document.mysite.variable` first you must `document.mysite = {}` – Piotr Müller Mar 28 '13 at 10:59