Skip to content Skip to sidebar Skip to footer

Javascript Form Validation Based On Php Session Variables

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. Obviou

Solution 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.

Post a Comment for "Javascript Form Validation Based On Php Session Variables"