PeriodicalUpdater for jQuery

Here at 360innovate we’ve benefitted greatly from free and open source software.

Whether it’s the web server our sites run on or the operating system that runs the web server, free and open source software plays a huge part in the industry we work in.

And so, we present this jQuery plugin in an effort to give a little something back!

The Prototype javascript library features a very useful PeriodicalUpdater() function. This loads content at specified intervals, but if the content being pulled in doesn’t change, the interval gradually increases.

There are several benefits to this approach – it saves bandwidth, and can reduce the CPU usage on the client’s machine.

Unfortunately, there’s been no way to replicate this using jQuery…until now!

Let’s take a look at how it works.

Step 1 – Include the latest version of jQuery and the plugin.

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="jquery.periodicalupdater.js" type="text/javascript"></script>

Step 2 – call the function with the necessary options and a callback function

$(document).ready(function(){
   $.PeriodicalUpdater({
      url : 'random.php'
   },
   function(data){
      var myHtml = 'The data returned from the server was: ' + data + '';
      $('#results').append(myHtml);
   });
})

Here’s a list of all the options you can set:

url
URL for the ajax request. (Required!)

method
Can be either get or post. (Or GET or POST!)

sendData
Array of values to be passed to the page – e.g. {name: “John”, greeting: “hello”}

minTimeout
Starting value for the timeout in milliseconds.

maxTimeout
Maximum length of time between requests.

multiplier
Sets the amount of decay between ajax requests. If this is set to 2, the length of time between each request will double while the response doesn’t change.

type
Response type – can be text, xml, json etc – as with jquery.get or jquery.post.

Step 3 – Stop the requests!

Finally, you might want to stop ajax requests from PeriodicalUpdater – you can do so like this (assuming you had a link with id stop):

$('a#stop').click(function(e){
   e.preventDefault();
   clearTimeout(PeriodicalTimer);
})

We hope you find this plugin useful. It’s dual licensed under the GPL and MIT licences (just like jQuery), so please read them before you use this plugin.

View the demonstration

Download the plugin

Tags: ,

  • http://johnrdorazio.altervista.org/ Lwangaman

    I found this very useful, in fact I was using prototype on some websites I created to keep a clock on a calendar updated every minute, but when I wanted to try to use jquery in went into conflict with prototype. So this is a very useful function!

    I have one problem though, it is not working correctly in Internet Explorer, while in Firefox and Google Chrome it is working fine. My example is on http://johnrdorazio.altervista.org/SitoFlatnukePersonale/?lang=en&mod=
    The calendar block in the right column is using periodicalupdater to keep the time ticking. Works fine in Firefox and Chrome, IE instead gives me a fixed 19:20:41 every time and will not update!

    My php file has:

    and my jquery script has:

    $(document).ready(function(){

    var myclockurl = $(‘input#clockurl’).attr(“value”);

    $.PeriodicalUpdater({
    url : myclockurl,
    type : “text”
    },
    function(data){
    $(‘span#jqueryclock’).text(data);
    });
    })

    Any suggestions would be very welcome!

  • http://johnrdorazio.altervista.org/ Lwangaman

    I see that php code gets cut out, I’ll try posting it like this:

    *** echo date(“H:i:s”, time() + (3600 * $fuso_orario)); ***

  • http://johnrdorazio.altervista.org/ Lwangaman

    I already got the answer… It had to do with how IE handles page caching. “Check for newer versions of stored pages” has to be set to “every visit to the page” and not to “automatic”.

  • http://www.360innovate.co.uk John McCollum

    Thanks for your feedback Lwangaman, that’s something to watch out for. Also, I wouldn’t really recommend using this for a clock – by the time your ajax request gets back from the server, the time will have changed!

    Also, it will cause you to use more bandwidth than if you had a pure JS implementation.

    Still, thanks for the feedback!

  • Jarda

    Sorry for my stupid question, but and what about it when I need more than one PeriodicalUpdater on page? First have influence on second…

  • http://johnrdorazio.altervista.org/ Lwangaman

    As for the clock, it only updates every 60 seconds so it shouldn’t bog down the bandwith, and since it doesn’t display the seconds it’s not a problem if it’s a few seconds off.
    I haven’t had any problems with any of these browsers now (IE, Firefox, Chrome), but I have noticed a problem on one server, I have a website on server ilbello.com and my clock doesn’t update on their server. I’m supposing it’s a server problem because I haven’t had any problems on altervista or aruba.

  • http://johnrdorazio.altervista.org/ Lwangaman

    Then I have also found out that at times it is necessary to set the right headers on the page, which can also be done in php. I have read in some places that these headers should be used:

    header( “Expires: Mon, 26 Jul 1997 05:00:00 GMT” ); // disable IE caching
    header( “Last-Modified: ” . gmdate( “D, d M Y H:i:s” ) . ” GMT” );
    header( “Cache-Control: no-cache, must-revalidate” );
    header( “Pragma: no-cache” );

    In other places I have read that “Pragma: no-cache” is deprecated…
    Some say that if you don’t disable the caching correctly and you just add a unique id to the page each time you wind up filling up the server cache uselessly…
    I guess it can be a complicated issue!

  • Pingback: Diary of the Twitter Newbies | 360innovate Blog

  • jquery.periodicalupdater.js

    hello,
    U use the js file jquery.periodicalupdater.js, but where i can find it please?

  • http://johnrdorazio.altervista.org/ Lwangaman

    It’s on this same page! Just click on “download the plugin”.

  • http://johnrdorazio.altervista.org/ Lwangaman

    @john mccullum
    btw, I noticed you opened a page on jquery plugins page for this plugin, but you didn’t upload it there, you just hint at it. Why don’t you upload it onto that page so it will be more accessible?

  • justin2

    Is there a way to change the parameters being passed to the URL (or change the URL itself) on each periodical request?

    This can be accomplished with prototype’s PeriodicalExeceutor by doing something like the following:

    var url = ‘http://www.example.com’;
    new PeriodicalExecuter(checkSomething, 60);

    var checkSomething = function() {
    ajax = new Ajax.Request(url + “?format=xml”, {
    method:”get”,
    asynchronous:true,
    parameters:”&id=” + latestId,
    frequency:60.0,
    decay:1.0,
    onLoading:displayLoading,
    onSuccess:displaySomething,
    onException:processException,
    onFailure:processError
    });
    }

    var displaySomething = function(response) {
    //process response

    //update the parameters being sent in the next request
    ajax.options.parameters=”&id=” + latestId + “&” + encodeURIComponent((new Date()).getTime());
    }

  • http://www.360innovate.co.uk John McCollum

    @justin2 – No, periodical execution of functions isn’t planned for this plugin. I may write a similar plugin in the future that emulates PeriodicalExecutor.

    @Lwangaman – thanks for your support! I do intend to upload the plugin to jquery.com shortly.

  • Pingback: 10+ jQuery Plugin

  • Pingback: JQuery PeriodicalUpdater | Enfranchised Mind

  • Pingback: Updater avec JQuery du contenu à jour

  • fede

    thanks great work, but you have to set PeriodicalTimer as a global variable of the plugin to allow stop the Timer with clearTimeout

  • Pingback: 11 useful jQuery Plugins for web development | Webmaster 9

  • Pingback: 10+jQuery Plugins per Web Designers | Web Design

  • Pingback: Список нужных плагинов для jQuery | WebDuty

  • Pingback: [jquery] mehrere PeriodicalUpdater - Javascript & Ajax @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe

  • bill

    Metering down the requests based on “lack of change from last request” is somewhat arbitrary and of doubtful usefulness. It all depends on your application I suppose, but a better metric would be USER ACTIVITY ON THE CLIENT SIDE – if no user there, then no need to poll quite as often,

  • http://www.dniwebdesign.com/ Dawson

    I am trying to have this multiple times on a page, however the second one keeps updating the first one as well. The divs have different ids and everying, yet I cannot figure out what's wrong.

  • Pingback: jQuery und Periodical Updater - Javascript & Ajax @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe

  • lea

    its ok, i use html() instead of append(), but i am jus wondering maybe this is just me, but this does this work in IE? because it is not working for me.

  • freezone45

    How can I use multiple instances of this plugin? I mean I want to have a periodical updater of 2 different divs' with two different sources.
    Thank you! That's super!

  • http://dsgs.ru/ peter

    good

  • Pingback: Cakephp logger plugin « nerdnotes.org