user2839573
user2839573

Reputation: 67

Session not updating until refresh

I'm trying to use an AJAX call to update a session variable, then redirect and get that variable on the next page. My problem is that once the page has redirected, the session is not updated until I refresh.

I think this might be to do with the fact that the session is the first thing that gets loaded, but I can't find a way around it. Here is my relevant code:

Input page

$.post('save.php', {data:$input})
    .done(function() {
        window.location.replace('result.php');
    }
);

save.php

session_start();

// make sure previous value has been deleted
unset($_SESSION['word']);

$_SESSION['word'] = $_POST['word'];

result.php

session_start();

$data = $_SESSION['word'];

print_r($data);

Thanks!

Upvotes: 1

Views: 4362

Answers (1)

Niki van Stein
Niki van Stein

Reputation: 10724

I think @skywalker has a very good point, but if you want to do it with ajax like now:

In your php file where you save the session change it to

session_start();

// make sure previous value has been deleted // <--- not needed
unset($_SESSION['word']);

$_SESSION['word'] = $_POST['word']; 

session_write_close();  //<---------- Add this to close the session so that reading from the session will contain the new value.

To explain: the session is stored in files on the server. When you edit the session, the files are locked for writing but not for reading. When the server did not write all the changes yet to the session files and the next php script tries to read the session, you will get the 'old' values. To force the server to write all changes to the session, close the session for writing before reading with the next script.

Upvotes: 1

Related Questions