How to abort ajax requests gracefully
by z3n on Jun.28, 2010, under Coding, Tips & Hints
Problem:
Ajax is great, everyone knows, but sometimes for network issues, server slowdowns or simply users issues request fails or keep loading for a long time. How to abort a request or all of them without needing to reload the whole page?
Solution:
First you need to throw all your ajax requests into a array, that way you can use it as api, so you can abort any “slow” requests, in my case i have a complex admin interface which sometimes bugs or get swamped with lots of requests at same time, usually due user related issues, so i added this “cancel” button which clears up all pending ajax requests, making the system more realiable. Before developing it i did a test on how it works, here’s the source:
<?php
// (c) z3n - R1V1@100628 - www.overflow.biz - rodrigo.orph@gmail.com
if (isset($_REQUEST['q'])) {
header('Content-Type: application/json; charset=utf-8'); // mandatory for jquery compatibility
if (!isset($_REQUEST['a']))
sleep(20);
echo json_encode(array("r" => 1));
die;
} else {
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var _ajax=[];
function do_dbg(msg) {
$("#dbg").prepend(msg+"<BR>");
}
function do_ajax() {
do_dbg("do ajax");
_ajax[_ajax.length] = $.ajax({data:"q=something",success:function(r,s) {
do_dbg("do ajax reply");
return;
}});
}
function do_ajax_fast() {
do_dbg("do ajax_fast");
_ajax[_ajax.length] = $.ajax({data:"q=something&a=other_thing",success:function(r,s) {
do_dbg("do ajax fast reply");
return;
}});
}
function kill_ajax() {
do_dbg("aborting all ajax");
for (var i in _ajax)
_ajax[i].abort();
}
$(document).ready(function(){
$.ajaxSetup({
url:"<?=$_SERVER['PHP_SELF']?>",
global:true,
type:"POST",
dataType:'json',
cache:false,
async:true,
timeout:12000000,
scriptCharset:"UTF-8"
});
});
</script>
</head>
<body>
<input type="button" onClick="do_ajax();" value="do ajax">
<input type="button" onClick="kill_ajax();" value="kill ajax">
<input type="button" onClick="do_ajax_fast();" value="do ajax fast">
<BR><BR>
<span id="dbg"></span>
</body>
</html>
<?php
}
?>
Have fun!