Ole Haugset Ole Haugset - 3 months ago 17
jQuery Question

Setting a polling-script while ajax is running not working

I have a ajax script that on occations can take from 10-30 seconds to execute. During its execution of a PHP file, the PHP script sets a session parameter to different states. The idea behind this is to have a second ajax run async with the first, to update the current workflow.

To do this I am using the following with ajaxStart and ajaxStop:

function getScriptState(){
url : "/modules/core.iris/ajax/getState.ajax.php",
type : "GET",
dataType : "json",
async : true,
global: false,
success : function (d){
if( $('#statusMsg').length !== 0 ){
if( typeof d.statusMsg !== "undefined" ){
$('#statusMsg').html( d.statusMsg );
function clearScriptState(){
url : "/modules/core.iris/ajax/clearState.ajax.php",
var loaderMsg = null;
$( document ).ajaxStart(function() {
loaderMsg = setInterval( getScriptState, 500 );
$( document ).ajaxStop(function() {
clearInterval( loaderMsg );

The script calling the longrunning PHP script is as follows:

url : "/modules/core.wages/ajax/wagesLines.ajax.php",
async : true,
type : "POST",
data: weeks,
dataType: "json",
success : function(d){

The problem is, that getScriptState() isnt actually running async with the above script. It actually doesnt return the state until a millisecond before the longrunning ajax call has finished.

From my console log when it finishes, it looks like it has run twice before longrunning script has finished, but this doesnt reflect in the DOM.

Here is a picture of the network timeline in chrome. Showing the getState getting called once, then the result of wageLines.ajax.php is run, and then getState is run again several times. Those several times should infact be before the wageLines.ajax.php since it was not finished fetching the data:

enter image description here

As shown in this screenshot, the problem is that all of the calls to getState.ajax.php are being run until the wagesLines.ajax.php is done. So no matter if getState.ajax.php only takes 100ms to execute, it doesnt finish until wagesLines.ajax.php does.

Anyone got any ideas?


This problem occurs due to the fact that both scripts being called are trying to access the same PHP session.

PHP by default locks the session until the script is finished.

It can be fixed by using session_write_close().

Reference: Long running background PHP script blocks other PHP pages until it is finished