0

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?

3
  • make sure you're passing the data using for example : data: {el_id: "test"}, Commented Sep 17, 2018 at 8:38
  • make sure also that the session creation work statically like $_SESSION['element_ids'] = "test". Commented Sep 17, 2018 at 8:39
  • @ZakariaAcharki I checked "data" with "test" - still not working. And session creation works statically. Commented Sep 17, 2018 at 8:45

1 Answer 1

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:

<?php
    session_start();
    echo (isset($_SESSION['element_ids'])) ? $_SESSION['element_ids'] : 'not yet set';
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Accidentally caught this while checking for possible errors in data: {el_id: el_id}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.