Reputation: 28505
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?
Upvotes: 3
Views: 182
Reputation: 40916
are variables shared across multiple ajax requests to the same PHP file, or are they unique per request?
The PHP variables are reset with each request, so you don't need to worry about one request messing with the values from another request.
And what about SESSION variables and their initialisation?
$_SESSION
data is different. It lives somewhere on disk or in memory outside the PHP process, just like database data. Therefore, like the database it survives across requests, asynchronous or otherwise, and will be modified on a first come first served basis.
In your example though, you set $_SESSION['values'] = array();
on each request, so it will be reset to an empty array. If you had just pushed new values into it, the values from the previous requests would survive (at least until the session is destroyed).
Another important point about sessions: while the session is live, PHP locks the underlying file. So if your request takes a long time to serve and another request for the same session comes in, you will run into trouble. In this scenario, your best bet is to release the session file when you're done with it, for instance early in the script. You can always reload it towards the end to store the results of the script.
session_start();
... // do your session work early
session_write_close();
... // continue with your long script
can asynchronous requests to the same file influence each other?
Yes! if processing takes a long time working with a file, another process could error. Consider this script:
//allow script to run for a long time (or PHP might kill it)
set_time_limit(35);
$file = fopen("test.txt","w+"); //open file
flock($file,LOCK_EX); //set exclusive lock.
sleep(30); //sleep for 30 seconds
flock($file,LOCK_UN); //release lock
fclose($file);//close the file
If another request comes in and tries to open this file while this process is sleeping, you will have a problem.
Upvotes: 2
Reputation: 439
Let's run a test and see:
JS
for (ajax_var=1; ajax_var < 4; ajax_var++) {
$.ajax({
url: 'variable.php',
type: 'POST',
data: { 'ajax_var': ajax_var },
success: function(resp) {
console.log(resp);
}
});
}
PHP
if(!isset($_SESSION)) { session_start(); }
$ajax_var = $_POST['ajax_var'];
$_SESSION['var'] = $ajax_var;
$data = [];
for ($php_var = 1; $php_var < 4; $php_var++) {
array_push($data, "Ajax Variable = " . $ajax_var);
array_push($data, "PHP Variable = " . $php_var);
array_push($data, "Session Variable = " . $_SESSION['var']);
array_push($data, " ");
}
print_r($data)
CONSOLE
Array
(
[0] => Ajax Variable = 1
[1] => PHP Variable = 1
[2] => Session Variable = 1
[3] =>
[4] => Ajax Variable = 1
[5] => PHP Variable = 2
[6] => Session Variable = 1
[7] =>
[8] => Ajax Variable = 1
[9] => PHP Variable = 3
[10] => Session Variable = 1
[11] =>
)
variable_test_run.html:20
Array
(
[0] => Ajax Variable = 2
[1] => PHP Variable = 1
[2] => Session Variable = 2
[3] =>
[4] => Ajax Variable = 2
[5] => PHP Variable = 2
[6] => Session Variable = 2
[7] =>
[8] => Ajax Variable = 2
[9] => PHP Variable = 3
[10] => Session Variable = 2
[11] =>
)
variable_test_run.html:20
Array
(
[0] => Ajax Variable = 3
[1] => PHP Variable = 1
[2] => Session Variable = 3
[3] =>
[4] => Ajax Variable = 3
[5] => PHP Variable = 2
[6] => Session Variable = 3
[7] =>
[8] => Ajax Variable = 3
[9] => PHP Variable = 3
[10] => Session Variable = 3
[11] =>
)
It seems as though the first php script is completed before the second php script is even started. However I am running this on a local server and a live server might have a slightly slower response than the javascript code. But the odds of two scripts aligning and causing overlap is slim to none. I'm sure a session variable is more likely to have overlaps but I've never really understood why you would need to loop an ajax call in a real world example.
Upvotes: 0
Reputation: 564
they are unique per request. you can use sessions, cookies, database to collect the data of the separate requests.
sessions will work as the each ajax is essentially the same as your browser doing a POST/GET and receiving a response, except its all happening in JS.
in php you can also detect if its AJAX(xmlhttprequest) here aside to just including a variable to identify it as ajax. (none of which appear to be completely fool proof).
more info on wiki here
another sof query about ajax vs normal requests here
and more here
Upvotes: -1