allwyn.menezes
allwyn.menezes

Reputation: 804

Changes to $_SESSION without page reload

I have two $_SESSION variables declared as array in index.php, say:

$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);

I make a AJAX call from index.php to result.php, where values of session variables are changed to, say:

$_SESSION['a'] = array(2,3,1,4);
$_SESSION['b'] = array(5,6);

What I do is, I remove the first element from both the arrays and append it back to first array, $_SESSION['a'].

On successful AJAX call, I want to print the first elements of both the variables in index.php. Is it possible?

Upvotes: 0

Views: 149

Answers (2)

user849137
user849137

Reputation:

This is pretty straight forward.

In your results.php you simply returned the new data with a bit of JSON.

result.php:

//set the session vars to whatever here....

//now, return them. In the example, I shall assign your session vars to temp vars.

$sessA=$_SESSION['a'];
$sessb=$_SESSION['b'];

echo json_encode(array('a'=>$sessA,'b'=>$sessb));

And now in your AJAX (assuming you're using jQuery):

$.getJSON('results.php', function(data){

alert(data.a);
alert(data.b);

});

And there you have it.

EDIT:

In your index.php, you say you set the session vars to the original value. But in your comments, you say you want to use the new vars in index.php. This won't be possible if you are setting them to the original value in index.php on every request. What you should do is check if they're already set first, and then do what needs to be done. Like this:

instead of:

$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);

Do this:

if ( isset($_SESSION['a']) === false && isset($_SESSION['b']) === false )
{

# - The vars are not already set...so it's okay to set them to its original value.

$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);

}

Upvotes: 0

Peon
Peon

Reputation: 8030

Yes, on a successful ajax call, you can do that.

Upvotes: 2

Related Questions