article

Friday, April 29, 2022

How to get PHP Session Value in jQuery

How to get PHP Session Value in jQuery

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

getssionjquery.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//getssionjquery.php
<!DOCTYPE html>
<html>
<head>
    <title>How to get PHP Session Value in jQuery</title>
</head>
<body>
<?php session_start(); ?>
<div class="container">
    <h1 class="page-header text-center">How to get PHP Session Value in jQuery</h1>
    <div class="row">
        <div class="col-6">
            <h3>Set 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>
  
    <input type="hidden" value="<?php
        if(isset($_SESSION['value'])){
            echo $_SESSION['value'];
        }
    ?>" id="session">
</div>
<script>
$(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);
        }
    });
});
</script>
</body>
</html>
session.php
1
2
3
4
5
6
7
8
9
//session.php
<?php
    session_start();
  
    $session_value=$_POST['session_value'];
    $_SESSION['value']=$session_value;
  
    header('location:getsessionjquery.php');
?>
unset.php
1
2
3
4
5
6
//unset.php
<?php
    session_start();
    unset($_SESSION['value']);
    header('location:getsessionjquery.php');
?>

Related Post