Skip to content

Instantly share code, notes, and snippets.

@ngugijames
Forked from handerson/simplepolling.js
Created October 28, 2015 07:23
Show Gist options
  • Save ngugijames/f63a580a13faa65d0661 to your computer and use it in GitHub Desktop.
Save ngugijames/f63a580a13faa65d0661 to your computer and use it in GitHub Desktop.
Simple AJAX Polling jQuery Plugin
//Simple AJAX Polling jQuery Plugin
// example usage:
/* $.ajaxPoll({
url: "/path",
type: "GET",
interval: 250,
maxAttempts: 25,
successCondition: function(result) {
return result != "processing";
},
success: function(data) {
$('#container').replaceWith(data);
}
});
*/
jQuery.ajaxPoll = function(user_options){
var options = {
interval: 30000,
maxAttempts: 15
}
jQuery.extend(options, user_options);
var attempts = 0;
options.success = function(data, status) {
if (options.successCondition(data)) {
if (options.successCallback){
options.successCallback(data, status);
}
return;
}
attempts++;
if (attempts > options.maxAttempts) {
return;
}
setTimeout(function() { jQuery.ajax(options) }, options.interval);
};
jQuery.ajax(options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment