Tag Archives: jquery

Endless polling ajax gotchas with recursive calls

There’s a pretty good piece on how to make your page continually update over here which works pretty well. With one problem. In my mind, a rather major problem. If you ever have an exception in the success, error or complete handlers inside the $.ajax() call, javascript error handling junks the rest of the function, and you never make the recursive call.

Old and Busted

(function loopsiloop() {
   setTimeout(function() {
       $.ajax({
           url: 'foo.htm',
           success: function(response) {
               // BANG! TypeError Cannot read property 'xxx' of null
               console.log(response.expected_property);
           },
           complete: function() {
               // Only works if success didn't throw an exception
               loopsiloop();
           }
       });
   }, 5000);
})();

In certain conditions, jquery’s success handler gets called with what could hardly be called a successful response. Maybe you got a 404 page instead of the json you were expecting, or whatever. Fair bet that your handler code wasn’t expecting that. Fair bet that it was actually transient (rebooting the server for instance) Fair bet that you actually want it to just try again in five seconds.

Well, sucks to be you, but the first time your success handler throws any sort of exception, javascript just ate your function.

New and Sexy

Use jQuery’s deferred objects

(function loopsiloop_sexy() {
        setTimeout(function() {
            $.ajax({
                 url: 'foo.htm',
                success: function(response) {
                    // BANG! (we didn't stop it throwing TypeErrors)
                    console.log(response.expected_property);
                }
            }).always(function() {
                // This will always be called, regardless of exceptions in the ajax call
                loopsiloop_sexy();
            });
        }, 5000);
    })();

Note that the .always call is outside the anon function that $.ajax is calling. So now, even when your success/error/complete methods explode, you haven’t broken the endless loop. And as soon as your server starts serving what you expected again, it all starts working again. Yay!