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

Bookmark and Share

Tags: ,

  • http://twitter.com/ronalddevera/statuses/1318335824 ronalddevera (Ron DeVera)

    PeriodicalUpdater for jQuery, ported from Prototype! Tweaks Ajax polling frequency based on whether content has changed. http://is.gd/n5Jr

  • 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!

  • http://www.360innovate.co.uk/blog/2009/04/diary-of-the-twitter-newbies-7/ Diary of the Twitter Newbies | 360innovate Blog

    [...] several conversations and tweets about 360innovate on Twitter, many regarding @johnmcc’s JQuery 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.

  • http://yloz.eu/2009/06/19/10-jquery-plugin/ 10+ jQuery Plugin

    [...] jQuery Periodical Updater | Demo Share and Enjoy: [...]

  • http://enfranchisedmind.com/blog/posts/jquery-periodicalupdater/ JQuery PeriodicalUpdater | Enfranchised Mind

    [...] Unfortunately, such a beast doesn’t exist within the core JQuery code. I bitched about the lack of one on Twitter, and ddelponte resisted routing me to http://letmegooglethatforyou.com/?q=jquery+periodicalupdater and instead pointed out the #1 hit on Google: 360innovate.co.uk’s port. [...]

  • http://www.jordimir.com/ajax/updater-avec-jquery-du-contenu-1429 Updater avec JQuery du contenu à jour

    [...] A télécharger ici [...]

  • fede

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

  • http://www.webmaster9.com/2009-06/11-useful-jquery-plugins-for-web-development.html 11 useful jQuery Plugins for web development | Webmaster 9

    [...] jQuery Periodical Updater | Demo This plugin is a port of Prototype’s Ajax.PeriodicalUpdater() function, which sends timed Ajax requests to the server, with a built in decay between requests if the content doesn’t change. All options are configurable. [...]

  • http://www.ipwebdesign.it/2009/07/10jquery-plugins-per-web-designers/ 10+jQuery Plugins per Web Designers | Web Design

    [...] jQuery Periodical Updater | Demo [...]

  • http://webduty.ru/%d1%81%d0%bf%d0%b8%d1%81%d0%be%d0%ba-%d0%bd%d1%83%d0%b6%d0%bd%d1%8b%d1%85-%d0%bf%d0%bb%d0%b0%d0%b3%d0%b8%d0%bd%d0%be%d0%b2-%d0%b4%d0%bb%d1%8f-jquery.htm Список нужных плагинов для jQuery | WebDuty

    [...] PeriodicalUpdater [...]

  • http://www.tutorials.de/forum/javascript-ajax/343673-jquery-mehrere-periodicalupdater.html#post1778819 [jquery] mehrere PeriodicalUpdater – Javascript & Ajax @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe

    [...] im Gegensatz zu Prototype, leider nicht standardm

  • 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.

  • http://wp.oden.gr/programming/jquery/list-of-really-useful-plugins-for-jquery-developers Oden’s Temple » Blog Archive » List of Really Useful Plugins For jQuery Developers

    [...] PeriodicalUpdater Adds ability to loads content at specified intervals, and if the content being pulled doesn’t change, it gradually increases interval to saves bandwidth and reduce the CPU usage on the client’s machine. [...]

  • http://www.tutorials.de/forum/javascript-ajax/347408-jquery-und-periodical-updater.html#post1800294 jQuery und Periodical Updater – Javascript & Ajax @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe

    [...] die den von prototype gewohnten periodischen Updater nachstellen. – ekko.periodicalupdater – jquery.periodicalupdater (360innovate) Ciao Quaese __________________ Vielleicht muss man manchmal vom Weg abkommen, um [...]

  • LuK

    Hi,

    thank you very much for this script, good work! I wanted to ask if it's possible so set the multiplier to something <1, means after the first interval has run out, it will check faster and faster? could this also be limited?

    thanks for your answer!

  • Name

    Any way to turn it off automaticlly based on the data?

  • lea

    Hey this is a great plugin, thanks! I was wondering if there is a way to make the data update, as new results are received, instead of append???

    Thanks again!

  • 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.

  • lea

    Its ok, i make GET into POST.

    Thanks again for your wonderful plugin!!!!

  • jaysmith123

    how do you make this work with multiple log files and multiple #result id's? ie #result_1, #result_2 etc and multiple log files: /etc/httpd/logs/access.log, /etc/httpd/logs/error.log

  • http://twitter.com/raganwald Reg Braithwaite

    Alas, Mobile Safari does not support JSON.parse, so if you want to use PeriodicalUpdater on an iPhone/iPod Touch, you need a workaround. jQuery 1.4.1 supports jQuery.paseJSON, so I changed line 126 of jquery.periodicalupdater.js to read:

    remoteData = jQuery.parseJSON(remoteData);

  • 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!

  • luk

    Sure it can be done =)…I use it like this on a site (radio) which needs to update the currently playing track, the intervals have to become shorter and shorter to achieve this in the way I want…so I modified the source a bit…

    first you need to comment out the following line:

    // settings.multiplier = settings.multiplier < 1 ? 1:settings.multiplier;

    this sets the multiper back to 1 if it's smaller than 1…we don't want that =)

    not sure about that (see the original code to verify), but I think I changed something in here too:

    if (timerInterval > settings.maxTimeout)
    {
    timerInterval = timerInterval * settings.multiplier;
    }

    if(timerInterval < settings.maxTimeout)
    {
    timerInterval = settings.maxTimeout;
    }

    I initialize it like this:

    $.PeriodicalUpdater({
    url: 'assets/load/load_ap.front.php',
    method: 'post',
    minTimeout: 80000,
    maxTimeout: 30000,
    multiplier: '0.75'
    …and so on…

  • http://dsgs.ru/ peter

    good

  • http://nerdnotes.org/2010/04/cakephp-logger-plugin/ Cakephp logger plugin « nerdnotes.org

    [...] jquery code (using the periodicalupdater plugin) that adds new lines to a div element when they appear in the log file, scrolls down so the [...]

  • http://www.deadlock.it/programming/javascript/jquery-rolling-and-polling/ jQuery Rolling and Polling | tips & tricks

    [...] 360innovate (GPL and MIT) rewrote PeriodicalUpdater for jQuery. [...]

  • gokul

    thank u

  • http://twitter.com/AnthonyLELONG Anthony LELONG

    Hi everybody!

    I’d like to define two different periodicalUpdater inside one web page, but the second one overwrite the first one. I tried to put them in two different js functions but it still doesn’t work.

    Does anybody have any idea?

    Thx.

    Anthony.

  • http://www.facebook.com/people/John-Aadeez/100002620262146 John Aadeez

    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,,.Used
    Fiat 500 prices