3

My project is basically like a Reddit feed that updates in real-time. I'm trying to use AJAX to poll the server at intervals for updates on 15 items at a time.

I wrote a for loop but it caused the browser to lock up (I'm guessing too many XHRs?).

How can I poll each item on the Reddit-esque feed without locking up the browser? What is the most efficient way to do this?

Should I use long-polling if there are 100+ clients using the web app at the same time? Or should I opt for smart polling (increasing the wait time between requests if no data)?

Thanks! I'm still new to AJAX!

for (var i=0; i < id_array_len; i++) {
        // Grab current reply count

        var reply = $("#repl"+item_id).html();
        var url= *php function here*

        var ajaxRequest;

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }

        ajaxRequest.onreadystatechange = function(){
            if (ajaxRequest.readystate == 4){
                live_feed_data_tot = ajaxRequest.responseText;

                if (live_feed_data_tot.trim() == "no change" || live_feed_data_tot.trim() == "no meme" || live_feed_data_tot.trim() == "no response"){

                    console.log("(no update)");

                } else {

                    var live_feed_data = live_feed_data_tot.split(',');
                    if (live_feed_data[1] == 'reply') {
                        // Reply count has changed
                        new_reply = live_feed_data[0].trim();

                        // Update actual number
                        $("#repl"+item_id).html(new_reply);

                    }
                }
            }
        }

        ajaxRequest.open('POST', url, true);
        ajaxRequest.send();
Delos Chang
  • 1,823
  • 3
  • 27
  • 47

2 Answers2

3

Use longpolling with a long (appropriate for your app of course) timeout. Your call needs to be asynchronous of course. As long as there is no data to deliver, the server holds the answer back, until the timeout is about to be reached. As soon as the client gets an answer, trigger the next longpoll in your complete()-Block. This way you can minimize the number of requests.

EDIT: after seeing your code i see you use native ajax but use jQuery for selecting. I suggest you to use jQuery for your ajax requests as well (jQuery .ajax() Doku).

Your code should look something like this:

function doAjaxLongpollingCall(){

   $.ajax({
     url: "...",
     timeout: <prettylong>,
     success: function(){
       //process your data
     },
     complete: function(){
       doAjaxLongpollingCall();
     }
   });
}
Christoph
  • 50,121
  • 21
  • 99
  • 128
  • Thanks for the suggestions. Two questions if you don't mind answering... 1) I heard long-polling isn't very scalable when clients >100+. Is this true? 2) Thanks for the jQuery suggestion -- just wondering why you suggest that I use jQuery for my AJAX requests as well? Thanks for your patience! – Delos Chang Mar 21 '12 at 19:37
  • @TheJagganator I don't mind: 1. Yes, longpolling is critical, because every client sends Requests to the server regardless if there is data to fetch or not. Nonetheless there are not much alternatives if you really need realtime updates. You need to tune it correcty (e.g. set the timeouts accordingly). Btw. even huge portals use longpolling. 2. Jquery does all the dirty work for you ( no need for browserswitches, callbackhandlers are included and so on). Effectively you can write jQuery Ajax Requests in 3Lines where you need 20Lines of native JS. – Christoph Mar 21 '12 at 19:45
  • @TheJagganator If you are interested, you might want to read into [SPDY](http://www.chromium.org/spdy). Firefox11 already has it, Chrome of course too, and even the Apache-Server supports it. Still very experimental though. – Christoph Mar 21 '12 at 19:46
  • The reason you heard long polling isn't scalable is because it ties up apache threads. Here's some good info: http://stackoverflow.com/questions/333664/simple-long-polling-example-code – Andy Groff Mar 21 '12 at 19:56
  • Thank you for the info -- so if the project still involves 100+ users, should I still stick with long polling? – Delos Chang Mar 21 '12 at 19:59
  • @TheJagganator Well, that really depends on your hardware and setup. I have not enough experience on my own to say Yes or No, but I would definitely give it a try. (If Facebook uses it, it has to be possible...somehow;) ) – Christoph Mar 21 '12 at 20:06
0

If you are doing a lot of users, switch to socket.io and save yourself the hassle. It uses websockets (which use a push mechanism) and does fallbacks to other mechanisms like flash sockets or long polling if thats not available in the browser. Requires you to create this piece of your app in node.js though.

Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
  • since websockets are not supported by IE it pretty much comes down to ajax longpolls (or perhaps flash if installed). Looks interesting though, maybe I'll give it a try. – Christoph Mar 21 '12 at 20:48
  • That's why it auto falls back w/o any interaction from the dev. Ensures compatibility with IE6 and up. – Jan Jongboom Mar 21 '12 at 21:46