How to get PHP Session Value in jQuery

Getting Started

Please take note that Bootstrap and jQuery used in this tutorial are hosted so you need internet connection for them to work.

index.php

This is our index which contains our form to set up our session.
  1. <?php
  2. ?>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <title>How to get PHP Session Value in jQuery</title>
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  8. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  9. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  10. </head>
  11. <body>
  12. <div class="container">
  13. <h1 class="page-header text-center">How to get PHP Session Value in jQuery</h1>
  14. <div class="row">
  15. <div class="col-md-6 col-md-offset-3">
  16. <h3 class="text-center">Set our Session Value ( $_SESSION['value'] )</h3>
  17. <form method="POST" action="session.php">
  18. <input type="text" name="session_value" class="form-control" placeholder="Input Value" required>
  19. <div style="margin-top:10px;">
  20. <button type="submit" class="btn btn-primary">Set Value</button> <a href="unset.php" type="button" class="btn btn-danger">Unset Value</a>
  21. </div>
  22. </form>
  23.  
  24. <button type="button" id="checkSession" class="btn btn-info" style="margin-top:30px;">Check Session in jQuery</button>
  25. </div>
  26. </div>
  27.  
  28. <!--this is our reference in getting our session-->
  29. <input type="hidden" value="<?php
  30. if(isset($_SESSION['value'])){
  31. echo $_SESSION['value'];
  32. }
  33. ?>" id="session">
  34. </div>
  35. <script src="session.js"></script>
  36. </body>
  37. </html>

session.php

This is our PHP code in setting up our session.
  1. <?php
  2.  
  3. $session_value=$_POST['session_value'];
  4. $_SESSION['value']=$session_value;
  5.  
  6. header('location:index.php');
  7. ?>

unset.php

This is our PHP code to unset our session.
  1. <?php
  2. unset($_SESSION['value']);
  3. header('location:index.php');
  4. ?>

session.js

This is our jQuery code for checking the current value of the session.
  1. $(document).ready(function(){
  2. //check session
  3. $('#checkSession').click(function(){
  4. var session = $('#session').val();
  5. if(session == ''){
  6. alert('Session not Set');
  7. console.log('Session not Set');
  8. }
  9. else{
  10. alert('Current Session Value: '+session);
  11. console.log(session);
  12. }
  13. });
  14. });
That ends this tutorial. Happy Coding :)

Add new comment