jQuery Polling plugin
by sethtrain
I wanted to create a chatting application and decided to create a jQuery polling plugin specifically for that purpose. I don’t know for sure if this is useful to anyone else but it works for me.
(function($) {
$.fn.poll = function(options){
var $this = $(this);
// extend our default options with those provided
var opts = $.extend({}, $.fn.poll.defaults, options);
setInterval(update, opts.interval);
// method used to update element html
function update(){
$.ajax({
type: opts.type,
url: opts.url,
success: opts.success
});
};
};
// default options
$.fn.poll.defaults = {
type: "POST",
url: ".",
success: '',
interval: 2000
};
})(jQuery);
*Usage*
$("#chat").poll({
url: "/chat/ajax/1/messages/",
interval: 3000,
type: "GET",
success: function(data){
$("#chat").append(data);
}
});
Comments
how do i unbind, the plugin once i’m done with polling.
unbind() doesn’t work.
Well, setInterval returns an interval id that you can store and then run clearInterval(setIntervalID) to turn off the polling.
[...] jQuery Polling plugin by Buntin.org [...]
Great little plugin, my previous method made the browser unresponsive as it made continuous ajax requests to the server. This was just what I was looking for. Thanks