1

I wanted to use HTML links to change a session variable in PHP. To do this, I set up an HTML "a" tag that would call a javascript function that looks like this:

function changeValue(name){
  data = "key='person'&value=" + _name;
  $.ajax({
      url: www_root + "/funcs.php?func=set_session_var",
      type: "post",
      data: data,
      success: function(data){
          console.log(data);
      }
  }); 
  }

Then, I had the funcs.php script which had the set_session_var function like this:

function set_session_var(){
   session_start();
   $key= trim($_GET["key"]);
   $value= trim($_GET["value"]);
   $_SESSION[$key] = $value;
   session_write_close();
   echo $key;
}

Then, the original php/html page would reload, but it would first load an external page (call it item.php) that settled all of the php session stuff. Looks like this:

session_start()
$session_id = session_id();
$sc = $_SESSION['person'];

However, the $sc variable always shows up as empty, despite the AJAX success function returning the right value. I've checked the session_id's for both scripts, and they are the same. I have also tried to set a session variable in item.php, and it persists. It's just that when I set a session variable using the funcs.php script it doesn't save.

Any and all ideas are appreciated!

0

1 Answer 1

3

You're sending quotes:

data = "key='person'&value=" + _name;
            ^------^

which means you're effectively doing:

$_SESSION["'person'"] = $value;
           ^------^-

Note that those single quotes have become PART of the session key name.

Try

data = "key=person&value=" + _name;
            ^----^--- no quotes

instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked beautifully. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.