kulan
kulan

Reputation: 1391

Passing JavaScript to Session variable

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:

$(".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

<?
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?

Upvotes: 0

Views: 56

Answers (1)

Carl Binalla
Carl Binalla

Reputation: 5401

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:

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

Upvotes: 2

Related Questions