Filkor
Filkor

Reputation: 642

Session update through multiple ajax calls

"The Problem:"
I call with ajax a handler.php file multiple times.

In the handler.php I have:

session_start();
$_SESSION['foo'] .= 'abc';

echo 'Session var: '.$_SESSION['foo'].'<br>';

Now, what I see is:

Session var: abc
Session var: abc
Session var: abc
... etc

Instead of:

Session var: abc
Session var: abcabc
Session var: abcabcabc

Whats the problem?
I hope you get the point:)

EDIT: I forgot to mention that sometimes I get the second (what normally expect), but most of the time I get the first version.

Upvotes: 3

Views: 2411

Answers (3)

BrentW
BrentW

Reputation: 141

I know this is a super-old question, but I happened upon it while looking to confirm what I had read earlier today, after running into the same behavior.

For my application, we are already using session_start() and are handling the session with custom database handlers. But we were still getting errors when recording data to the session in various AJAX requests.

The problem with running concurrent AJAX requests that manipulate session data is that PHP by default only allows one script to have access to the session at a time: from the time it calls session_start() to the time it exits or otherwise calls session_write_close(). When you have multiple AJAX requests happening simultaneously that need to write to the session, they can step on each other and you end up with incomplete data.

This explains it better than I can: [ http://konrness.com/php5/how-to-prevent-blocking-php-requests ].

My particular solution was to store the data outside of session (elsewhere in the database) so that the other AJAX requests wouldn't step on my changes.

Upvotes: 0

Filkor
Filkor

Reputation: 642

I found the solution... so after 4 months I can answer it :)

The solution seems very easy but I did not think about it first. I thought it was a "deeper" problem, because my code is very long.. So the solution was to include session_start(); in the "index.php" file, (where you call the ajax itself or where you included the .js file). I hope it helps if someone in the future run into these silly "simptoms".* So, even if you don't use sessions in the "index.php" file, you have to include session_start() there if you wanna use sessions in the ajax "handler" php file.

(You have to include session_start(); to hander.php too, of course.)

Upvotes: 0

Maxime Pacary
Maxime Pacary

Reputation: 23041

Maybe define $_SESSION['foo'] as an empty string before appending something to it:

session_start();

// prevent caching
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

if (!isset($_SESSION['foo']))
  $_SESSION['foo'] = '';

$_SESSION['foo'] .= 'abc';

echo 'Session var: '.$_SESSION['foo'].'<br>';

Check as well that Cookies are enabled on your browser.

Upvotes: 2

Related Questions