Ajax is, by definition, an asynchronous request to the server. But what does this mean with respect to variables in a PHP file?
Let's say we have an Ajax request in a for loop. The request for each iteration is identical, except for the input that differs slightly (in this case someField
).
for (var iOuter = 0; iOuter < 3; iOuter++) {
(function(i) {
myArrayVariable['someField'] = i;
$.ajax({
type: 'POST',
url: 'someurl.php',
data: myArrayVariable
})
.done(function() {
console.log("Finished " + i);
})
.fail(function(jqXHR, textStatus, error) {
console.error(error + ": " + textStatus);
});
})(iOuter);
}
In PHP, then, we could have this:
$val = $_POST['someField'];
$values = array();
for ($i = 0; $i < 10; $i++) {
push($values, ($val+$i));
}
My question is: because it is an asynchronous request, does this mean that the scope of the variables is shared across the different requests? In other words, would $values
contain all values for all requests (when the loop has finished in each request), or is it unique per request?
In extension, what about modifying SESSION variables? Those ought to be shared, I assume? So if we had replace the above snippet by something like below would the $values array then have all values?
$val = $_POST['someField'];
$_SESSION['values'] = array();
for ($i = 0; $i < 10; $i++) {
push($_SESSION['values'], ($val+$i));
}
OR is it possible that, because some small time difference, even though the first initialised request has already written a value to the array, the second request re-initialises the session variable as an empty array? So values are possibly lost?
To summarise: are variables shared across multiple ajax requests to the same PHP file, or are they unique per request? And what about SESSION variables and their initialisation? When should you be careful when using variables/functions in PHP if you know that you are using that file in an ajax request? Or, generally: can asynchronous requests to the same file influence each other?