O'Reilly

Periodical AJAX Requests Using MooTools 1.2

By on  

Every browser I have, both at work and at home, has its default homepage setting set to NetVibes. Why? Because NetVibes lets me decide what content I want on my homepage and it uses AJAX to update information, so I can keep the same window open in the background all day. NetVibes even refreshes page content periodically so a page refresh is never necessary. Using MooTools 1.2, you can achieve the same effect: periodical AJAX requests!

The MooTools 1.2 Code

var request = new Request({
	url: 'ajax-periodical.php?ajax=1',
	method: 'get',
	update: 'refresh-me',
	onComplete: function(response) {
		$('element-to-update').set('html',response);
	}
})

var doMany = function() {
	request.send();
};

doMany.periodical(5000);

The above code executes an AJAX request every 5 seconds, updating the element with the ID attribute of element-to-update.

Periodical may only be used on a function, so I place the AJAX request within a function. You may NOT call .send().periodical().

This functionality has many uses. I see WordPress do this many times while I write an article (auto-saving). What do you use this for?

Track.js Error Reporting

Upcoming Events

Recent Features

  • 5 More HTML5 APIs You Didnât Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

Incredible Demos

  • Image Protection Using PHP, the GD Library, JavaScript, and XHTML

    Warning: The demo for this post may brick your browser. A while back I posted a MooTools plugin called dwProtector that aimed to make image theft more difficult -- NOT PREVENT IT COMPLETELY -- but make it more difficult for the rookie to average user...

  • Redacted Font

    Back when I created client websites, one of the many things that frustrated me was the initial design handoff.  It would always go like this: Work hard to incorporate client's ideas, dream up awesome design. Create said design, using Lorem Ipsum text Send initial design concept to the client...

Discussion

  1. Viva Netvibes !
    Thanks for tip !

  2. Cool idea but what’s the point of using periodical() versus the standard JS setTimeout()?

    I need to read up on 1.2 (wish Aaron would update his mootorial) so I don’t think I’ve seen this function before. Is it just a nice wrapper of setTimeout/clearTimeout ?

  3. @Tim: Yes. Better than writing a bunch of Timeout stuff, in my opinion.

  4. Can this be used to retrieve data from a MySQL table?

  5. @Ahmed: Absolutely. You can make the request go to a PHP script that does anything you want!

  6. This is such a clean way to do it. I think I am going to give mootool a try for my next project. I like the syntax structure. Thanks for the tip and it does save you a lot of timeout call.

  7. Great article, David! I used perisitant communication in some of my past asp.net projects, mostly for displaying changes in a database that occurre frequently. I tried several options, but this one seems to be much cleaner than those. Have to try it with jQuery as well.

  8. Very nice David !
    But if you want generate an html content, please change :

    $('element-to-update').set('text',response);
    

    into :

    $('element-to-update').set('html',response);
  9. @Catar4x: Good call — I saw that last night but didn’t update it. Will now.

  10. @Tim regarding “I need to read up on 1.2 (wish Aaron would update his mootorial)”

    The mootorial has been updated, but it also got moved, check out mootorial.com

    @david regarding “Periodical may only be used on a function, so I place the Ajax request within a function.”

    I hate to be nitpicky but you don’t need the extra function..

    var request = new Request({
        url: 'ajax-periodical.php?ajax=1',
        method: 'get',
        update: 'refresh-me',
        onComplete: function(response) {
            $('element-to-update').set('html',response);
        }
    }).send();
    
    request.send.bind(request).periodical(5000);
    

    will work just as well

  11. the snippet I posted also has the advantage of not creating a new request object every five seconds ;)

  12. @Bryan: Good call with not creating a new request. I was looking at this again last night and noticed that as well.

  13. jensensen

    @Bryan J Swift: your latest code loads nothing ??
    @david: works well but there’s no refresh ¿¿

    btw. how to load external sources?

    Thank you!

  14. BenBois

    hi all,

    a variante with auto-submit form and mutli responses..

    var request = new Request({
        url: 'ajax.php',
        method: 'post',
        onComplete: function(fullresponse) {
            var pdt_id = $('form_pdt_id').get('value');
            var response= fullresponse.split('::');
            $('resultdi21').set('html',response[0]);
            $('resultdiv1').set('html',response[1]);
        }
    })
    var sendForm = function() {
        request.send($('yourformid'));
    }
    sendForm.periodical(5000);
    

    @Bryan J Swift
    your “bind” method returns empty POST paramswith form

    see you!

  15. mike

    “Request is not defined” –> var request = new Request({

    that’s what it’s giving me. Why is that??

  16. @mike: You don’t have the “Request” plugin within your Moo build.

  17. mike

    oh ok, how do i get that plugin for mootools 1.2 build? i can’t find it on their website.

    also, when i use mootools 1.1 build, my fade in function:

    var myFunction = function(){
        var div = $('featureContent').setStyles({
            display:'block',
            opacity: 0
        });
        new Fx.Style(div, 'opacity', {duration: 1000} ).start(1);
    };
    

    that will work, but when i use Mootools 1.2 build it says FX.Style is not a constructor.

    so my question is, how can i make the most recent build 1.2 work properly?

  18. mike

    I added the request plugin using the core builder.. it still says the Request is not defined.

  19. mike

    any help on that?

  20. Great script, thanks a lot. But it works on IE? On my computer doesn’t work :(. Any solutions for that? Please help.

  21. Tommix

    David, thanks for all your stuff it really helps to a lot of people out there who try to understand Moo.. Your examples very easy to understand. Thanks to commenters as well, cause without them we could’t create advanced features to David’s examples :)

  22. Jordi

    I need similar script for complete a spy-event system (example:http://www.meneame.net/sneak.php) but don’t have idea how to return timestamp value for next send to the request on the next intervals.

    please help!

  23. Rich

    Hi, this worked good but I had some caching issues with IE, the cache bug fix where you append a time string to the URL was appending the same value as the event parameters were already prepared so instead I just changed the line:

    request.send();
    

    To:

    request.send('r=' + $time() + $random(0, 100));
    

    This will generate a new unique timestring each time before its sent out. It seems to have cured my IE problems.

    May be helpful for someone else who was looking for a solution.

    Thanks for the help David on Periodical, it was very helpful.

    Cheers.

  24. Leo

    it seems doesn’t work in IE

  25. Wao, nice stuff!
    I’m facing a problem, let i have to send 1000 ajax requests. if i place the Ajax request inside a loop, my browser got stuck :(
    How can i make it in a way that, another request will make if one response returns?
    Thanks

  26. Tommix

    Rich – thank you very much for fix :)

  27. Davor

    Hi David,

    very good stuff. Do i can use this for a chat, because when i do a delay of 0.5 sec to get the new request, is that good? could i use for chat an other way or is this the only way to get requests in realtime?

  28. Ingalb

    Hi David,

    Thanks for this tip.

    is possible to have this script compatible for Mootools 1.12 ??

    Thanks

  29. @Ingalb:

    I have the Same Problem. Also I have This Issue With “Google Style Element Fading Using Mootools”

    Please help us.

    Thanks For The Tips.

  30. Chris

    Not sure why, but this does not work with IE…any thoughts?

    function update(cn)
    {
    var request = new Request({
    	url: 'status.php?cn='+cn,
    	method: 'get',
    	update: 'refresh-me',
    	onComplete: function(response) {
    		$(cn).set('html',response);
    	}
    })
    
    var doMany = function() {
    	request.send();
    };
    
    doMany.periodical(500);
    
    }
  31. dbaind

    @mike: Fx.Style was replaced by Fx.Tween in Mootools 1.2 ( see http://mootools.net/blog/2007/11/14/mootools-12-beta-1/ ). The syntax is not exactly the same for this new method. If, like me, you have a large site to mantain, then probably editting each Fx.Style call is not an option. I solved my problem with the following function, that I inserted in mootools library after its end:

    // Fix for Fx.Style constructor (transition from mootools 1.1 to mootools 1.2)
    Fx.Style = function(x,y,z){
    	var T = new Fx.Tween( x, y );
    	for( var x in T ) this[x] = T[x];
    	this.start = function(v,w){ T.start( y, v, w ); };
    };
    

    It’s worked ok for me so far, but do let me know if it doesn’t work for you as expected.

  32. LinKuFF

    What is the best between periodical() or startTimer() ( http://www.mootools.net/docs/more/Request/Request.Periodical ) ?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...

  • Tips you can Use to Build an Excellent eCommerce Experience

    There are many reasons to build a good eCommerce experience if you are planning to build an eCommerce website. Visitors can place items in their cart and leave your site without making a purchase. In fact, three out of every four of them will do so....