Reputation: 57
My ajax code is
var auto_refresh = setInterval(function () {
$.ajax({
type: 'post',
url: 'lib/nav.php',
data: 'c=autchk',
success: function (result) {
$('#test-div').html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
// I don't know how to display error message
console.log('Error: '+jqXHR+' '+textStatus+' '+errorThrown);
}
});
}, 9000);
The request is sometimes cancelled before reach the timeout. In the chrome log, the status of cancelled request is stalled. Then I read the explanation that lead me to this
Queueing. The browser queues requests when:
- There are higher priority requests.
- There are already six TCP connections open for this origin, which is the limit. Applies to HTTP/1.0 and HTTP/1.1 only.
Stalled. The request could be stalled for any of the reasons described in Queueing.
Is the problem because of that or something else?
EDIT :
I test the code in 3 browsers
I did not see any cancelled request in Microsoft Edge. There are more in Chrome than Firefox.
Upvotes: 3
Views: 6838
Reputation: 14179
All browsers apply limitation on concurrent calls to the same origin, there is already a well discussion on it: Max parallel http connections in a browser?
The thing is that you're implementing the auto refresh in a wrong way,
what you are using is being called: Polling
, you basically call the server periodically but sometimes could happen that you already have others call in progress and this will cause the cancellation.
Polling is a very old way to do this, you should have a look on WebSocket
s or Server Side Events
which are definitely the best ways to handle server-side changes and reflect them into the UI.
If you can't implement them, then, you may need for the Long Polling Strategy
which is an old but still valuable way.
here are other info: What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?
function auto_refresh(onSuccess, onError, onEnd, rate, times) {
onSuccess = onSuccess || $.noop;
onError = onError || $.noop;
onEnd = onEnd || $.noop;
rate = Number(rate) || 9000;
times = Number(times) || Infinity
function iteration() {
return $
.post('lib/nav.php', 'c=autchk')
.then(onSuccess)
.fail(onError)
.always(function() {
if(Number.isFinite(times)) {
times -= 1;
if(times <= 0) {
return onEnd();
}
}
return auto_refresh(onSuccess, onError, onEnd, rate, times);
})
;
}
return window.setTimeout(iteration, rate);
}
auto_refresh(function(result) {
return $('#test-div').html(result).promise();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2