<?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>
<?php $session_value=$_POST['session_value']; $_SESSION['value']=$session_value; ?>
<?php ?>
$(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); } }); });