Reputation: 756
Okey so I can't quite see how to do this but this is what I am trying to do. I need to update a SESSION that is used on multiply places on the website. I do this with ajax but when I change the SESSION it remains the same in the website as before the ajax call. here is an example:
index.php
<?php
session_start();
?>
<script>
function sessionUpdate()
{
//Do a get ajax call that send the 2 parameters to updateSession.php
}
</script>
<?php
$_SESSION['foo'] = "foo";
$_SESSION['bar'] = "bar";
echo"<div>";
echo"<p onclick="sessionUpdate()>Update Session</p>";
echo"{$_SESSION['foo']} {$_SESSION['bar']}";
echo"</div>";
?>
updateSession.php
<?php
session_start();
$_SESSION['foo'] = "new foo";
$_SESSION['bar'] = "new bar";
?>
Now, the sessions are used al over the site so I can't just replace the information from the ajax call in the example div with a innerHTML=data.responseText; at just that place. Anyway when I do this teh echo of the foo and bar sessions don't change, are they just static variables that can't be changed without a page reload or what is the problem?
Upvotes: 1
Views: 2433
Reputation: 12815
As far as I understand, you open index.php
and example div contains default values of session variables ('foo bar' in your example). After you click Update Session, doing innerHTML=data.responseText
you can see updated session values ('new foo new bar' according to example). But after you reload index.php - it shows 'foo bar' again. According to your code, you do not check if you should set default session variables. Try to replace in your index.php
<?php
$_SESSION['foo'] = "foo";
$_SESSION['bar'] = "bar";
echo"<div>";
With
<?php
if(!isset($_SESSION['foo']))
$_SESSION['foo'] = "foo";
if(!isset($_SESSION['bar']))
$_SESSION['bar'] = "bar";
echo"<div>";
Updated code will check if session variable is set (user open index.php at the first time). Once it is not set - default values will be assigned, but once that is done, it will not override any future changes (so, after ajax call foo and bar variables will be set and your code will not rewrite its values)
Upvotes: 2