Friday 30 September 2016

Extending $.ajax() to include retriesExtending $.ajax() to include retries

Left QuoteImagine you have a simple function that formats all of your ajax calls.

function runQuery(url, params) {
return $.ajax({
mimeType: "text/plain; charset=utf-8",
url: url,
data: params,
type: "GET",
dataType: "html"
});
}


And you use it the recommended way.

var request = runQuery("test.php", "id=7");

request.done(function(data) {
// success
});

request.fail(function(data) {
// failure
});


If this script is connecting over an unreliable connection, or your server is overloaded, it could occasionally timeout and your ajax request will fail. But, if you extend this function, it will detect the fail and automatically retry.

The extended function creates and returns a $.Deffered promise, and a IIFE that will either reject the promise or retry the request, depending on the value on retryNum.

function runQuery(url, params) {
var deferredPromise = $.Deferred();

(function runDeferredQuery(url, params, retryNum) {

console.log("----- Attempt "+retryNum+" -----");

$.ajax({
mimeType: "text/plain; charset=utf-8",
url: url,
data: params,
type: "GET",
dataType: "html",
timeout: 5000, // timeout = 5 seconds
success: function(data) { deferredPromise.resolve(data); },
error: function() {
// retry if < 3
if (retryNum < 3) runDeferredQuery(url, params, (retryNum+1));
else deferredPromise.reject(); // return fail
}
});
}(url, params, 1)); // call runDeferredQuery with retryNum=1

return deferredPromise.promise();
}


Both of these scripts can be tested using a function that sometimes takes longer than 5 seconds to complete.



$val = rand(1, 10);
sleep($val);
print "Timeout = ".$val." seconds";

?>


There you have it, ajax retries without the need for third-party libraries.Right Quote

Next article: Houses (30 May 2018)

CommentsComments

Add your comments

Name

Comments

Question

2 * 6 = (this security question stops automated submissions)