buntin.org

jQuery Polling plugin

23 September 2008

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

Related tags: jquery, plugin, polling

Comments

1 Barry says...

In your example you've got a trailing comma on the success function, causes it to fail in IE but works in firefox. Nice plugin.

Posted at 6:51 p.m. on October 27, 2008

2 seth says...

@Barry

Fixed. Thanks.

Posted at 3:35 p.m. on October 29, 2008

3 Steven says...

Great example!

Posted at 12:30 a.m. on October 30, 2008

4 Mark says...

Ahh....Somebody else has already done something like what I've been thinking doing. Maybe I'm not crazy!

BTW This is not showing up in jquery category.

Posted at 9:57 a.m. on November 19, 2008

About Me

I am a software developer at notifymd.com. Web application development is my professional passion.

Comrades

Latest Posts

Categories

Made with Django.