Passing JavaScript to Session variable

kulan

New Member
#1
I am trying to pass a variable to a php session variable, so I can access it later from other functions. I might have a totally approach, I'm not sure. What I want to do is to have my vaiable stored somewhere so I can access it anytime and anywhere within a session. This is what I have now:
Mã:
$(".small-item-card .bookmark").click(function(e){
        e.preventDefault();
        let el_id = $(this).attr("element-id");

        $.ajax({
            type: 'post',
            url: '/session.php',
            data: {el_id: el_id},
            success:function(data) {
                console.log(data);
            }
        });
PHP - session.php
Mã:
<?
session_start();

$element_id = (isset($_POST['el_id']) ? $_POST['el_id'] : "empty");

$_SESSION['element_ids'] = $element_id;

echo $_SESSION['element_ids'];

?>
When I open session.php page it prints "empty". What am I doing wrong?
 

Admin

Administrator
Thành viên BQT
#2
That is because when you open session.php, (isset($_POST['el_id']) ? $_POST['el_id'] : "empty"); will run, changing $_SESSION['element_ids'] to empty.

Your code is working as it should be. Try echoing $_SESSION['element_ids'] to the main page instead, and you will see that it contains the right value. Try something like this for quick debugging, put it at the top of your main page. AND don't open session.php:

Mã:
<?php
    session_start();
    echo (isset($_SESSION['element_ids'])) ? $_SESSION['element_ids'] : 'not yet set';
?>
 
Top