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);
    }
});