views:

24

answers:

1

I have a DB containing small news and a web app displaying these. I would like to update my page every 60s with a jquery.ajax or jquery.getJSON request .

My question is how should I pass the last id i received from the server to the next ajax request so that i got only newer news? Where do I store it (on the DOM, into a global var, or hidden field, ...)?

+1  A: 

Yes, you need to pass some argument that identifies the point from where to search for new records. This is typically handled by having the server return a sequential id or a timestamp with each Ajax response, such that the subsequent request will append this as an argument.

You can store this value in various ways, but since these are typically single-page applications which are not reloaded, a simple JavaScript variable is often sufficient. You could also use closures as in the following example, instead of using a global variable:

function fetchData(last_update_id) {
   $.ajax({
      url:      'fetch_data.php?last_update=' + last_update_id,
      method:   'GET',
      dataType: 'json',
      success:  function(data) {
         // Get the last_update_id from the server response.
         last_update_id = data.last_update_id;

         // Process your Ajax response...

         // Relaunch after 60s with the last_update_id argument.
         setTimeout(function () {
           fetchData(last_update_id);
         }, 60000);
      }
   });
}

If you go for this approach, you would initially call this function with a 0 or a -1 argument, or anything else as long as the server will understand that it is the first request. Then the function will auto manage itself, keeping the last_updated_id enclosed in a closure.

Daniel Vassallo
+1 for the interesting read on closures
Andrew Dunn
+1 , I like this closure way!! Is there some boundary effects ( like stack growing, more memory consumption , ...). Is it a well known pattern to poll this way ? How other apps are doing it ( facebook, stackoverflow )...
Dave