How to get PHP Session Value in jQuery
Submitted by nurhodelta_17 on Monday, November 27, 2017 - 21:27.
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.- <?php
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <title>How to get PHP Session Value in jQuery</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- </head>
- <body>
- <div class="container">
- <h1 class="page-header text-center">How to get PHP Session Value in jQuery</h1>
- <div class="row">
- <div class="col-md-6 col-md-offset-3">
- <h3 class="text-center">Set our Session Value ( $_SESSION['value'] )</h3>
- <form method="POST" action="session.php">
- <input type="text" name="session_value" class="form-control" placeholder="Input Value" required>
- <div style="margin-top:10px;">
- <button type="submit" class="btn btn-primary">Set Value</button> <a href="unset.php" type="button" class="btn btn-danger">Unset Value</a>
- </div>
- </form>
- <button type="button" id="checkSession" class="btn btn-info" style="margin-top:30px;">Check Session in jQuery</button>
- </div>
- </div>
- <!--this is our reference in getting our session-->
- <input type="hidden" value="<?php
- echo $_SESSION['value'];
- }
- ?>" id="session">
- </div>
- <script src="session.js"></script>
- </body>
- </html>
session.php
This is our PHP code in setting up our session.- <?php
- $session_value=$_POST['session_value'];
- $_SESSION['value']=$session_value;
- ?>
unset.php
This is our PHP code to unset our session.- <?php
- ?>
session.js
This is our jQuery code for checking the current value of the session.- $(document).ready(function(){
- //check session
- $('#checkSession').click(function(){
- var session = $('#session').val();
- if(session == ''){
- alert('Session not Set');
- console.log('Session not Set');
- }
- else{
- alert('Current Session Value: '+session);
- console.log(session);
- }
- });
- });
Add new comment
- 4840 views