Jump to content

Setting global session variable in $config->ajax block


Moebius
 Share

Recommended Posts

I'm having problem with setting global session variable in $config->ajax block.

To be more clear, here is example:

This will not work:

if($config->ajax) {
$_SESSION["TEST"] = "test"
}

and then after "normal " page rendering with no ajax I get nothing when trying to get session variable:

echo($_SESSION["TEST"]); // produces no output

however, if I set variable outside $config->ajax block:

if($config->ajax) {
// this is left blank to better describe context
} else {
$_SESSION["TEST"] = "test";
}

and then after "normal " page rendering with no ajax -  I get what I expect:

echo($_SESSION["TEST"]); // produces "test" as output.

So, what I want is set some global session variable inside ajax call and then reuse it's value during any page reload.

It's late and I probable miss something.

Link to comment
Share on other sites

ProcessWire API has methods for session handling: $session

To set your custom session variable you can use $session->set($name, $value) or $session->$name = $value and later retrieve it with $session->get($name) or $session->$name

So in your case it would be

if($config->ajax) {
    $session->test = "test";
}

Here test will only be set if you make an ajax call to the page. From your question it is not clear whether you made that ajax call before trying to get the test value on a normal page load.

To retrieve the value you can use

$test = $session->test;
  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...