Cancelling the current ajax request via a button click event!
I'd like cancel if my ajax request is taking long time with slower connections.
I show an overlay when .ajaxStart()
and if takes longer than five secons (i managed with setInterval
) a button appears on overlay that should cancel the current ajax request.
heres some of my code:
jqXHR = $.ajax({
url: 'includes/inc_ajax.php',
type: 'POST',
data: '&ajax=1&action=7',
success: function (txt) {
var cntr = $.parseJSON(txt);
$("#onlineppl").html(cntr.online);
$("#todayppl").html(cntr.bugun);
$("#totalppl").html(cntr.toplam);
}
});
$("#abortAjax").button({ icons: {secondary: "ui-icon-cancel"} }).click(function() {
$(jqXHR).abort();
});
Do I have to assign the $.ajax()
function to a var开发者_JAVA百科iable to abort it? I have many ajax request called by ajax too so i guess the browser can't track the same var name that causes the abort method not to work.
This is my first question here and I am a bit confused. Any help appreciated. Thanks.
Well, you culd try:
jqXHR.abort();
Whitout the $()
Note its not tested, i saw it somewhere
EDIT
Aah found it:
Stop all active ajax requests in jQuery
Yes, JavaScript is a prototype-based language and every object instance has a pointer. When two ajax calls start, your jqXHR only returns the pointer to the second ajax call. This is also indicated in this article where you have to get a token back from a function, so that you can refer to it to cancel it later.
Note - you can't really stop an AJAX request from processing on the server once it has been received. The server will continue processing the request even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress, except for implementing something manually (like a session property check that gets set by a different page).
So basically the server will still run, but the client browser will ignore the response - be aware that this also counts in your connections limitations to a domain (which is usually only TWO by default).
精彩评论