1

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!

user2839573
  • 67
  • 1
  • 4
  • 5
    Why do it with ajax, do it with post and update session var and then redirect with php? – skywalker Nov 12 '15 at 13:29
  • @skywalker I just posted a simplified version of my code (probably not clever) - I'm actually trying to pass an array, and I don't have a
    element on the webpage. In the end I used JSON.stringify() and this [post function](http://stackoverflow.com/a/133997/2839573) to pass the value. Thanks for the help!
    – user2839573 Nov 12 '15 at 14:09

1 Answers1

1

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.

Bas van Stein
  • 9,955
  • 3
  • 22
  • 60