I have a page with some user selectable options and a button that, when clicked, runs a PHP script and then refreshes a div with another PHP file that uses a session variable that is created at the end of the first PHP script. If the user presses the button again, with different options selected, the div is updated using the newly replaced session variable. The problem is that sometimes, perhaps 1 in 10 times or so, the old session variable data is loaded. I suspect that the second PHP file is catching the variable too early, before it has been updated, but I tried unsetting the session variable at various points with out any luck.
First PHP file:
session_start();
$needle = array();
foreach($_POST['checkboxes'] as $key => $value){
$needle[] = "$value";
}
// code that processes the values from needle and outputs $data
unset($_SESSION['data']);
$_SESSION['data']=$data;
Second PHP file:
session_start();
echo $_SESSION['data'];
Javascript:
$(".userdata").click(function() {
$.post("first.php", $("form#checkboxes").serialize());
});
$(function() {
$("#button").click(function() {
$("#div").load('second.php')
})
})
The problem is that in some cases the first PHP script has not finished running before you click the button that loads the second PHP script (like I implied before in my comment). The fact that this happens is related to how scripts are scheduled by the webserver (which is a different subject entirely).
You thus need to make sure that when you click the button that runs the second script, the first script has completely finished running.
Because in my knowledge, javascript does not allow blocking/signaling on a variable (like Java does), you’ll have to use a more ‘dirty’ technique called busy waiting.
The best way to do this, is to include an extra variable in the javascript you are using.
While ‘busy waiting’ is generally not considered the most elegant solution, I think you don’t have many other options in this case (except for serverside push, which is much more complicated). Additionally, you’ll probably only incur the extra 200 millisecond (or less, you can of course change this value) waiting time once or twice.
(side note: I assume that javascript is single threaded here, which is true in almost all cases: Is JavaScript guaranteed to be single-threaded?).