views:

48

answers:

3

I have a div the contents of which constantly changes based on a server side process. Currently I use jqeury load to poll the server every 3 seconds to get any updates.

This is what I have:

function poll() {
    reloadPage();
    setTimeout("poll();", 3000); 
}

function reloadPage() { 
      $("#mydiv").load(location.href + " #mydiv>*", "");
}

This works well in firefox but in IE, the load doesn't update the div, probably due to a caching issue. Is there a better way to do what I'm trying to do other than polling periodically?

+4  A: 

You need to change the URL for each request to prevent IE from caching the response.

For example:

function poll() {
    reloadPage();
    setTimeout(poll, 3000); 
}

function reloadPage() { 
    $("#mydiv").load(location.href + "?Timestamp=" + new Date() + " #mydiv>*", "");
}

Also, you shouldn't pass a string to setTimeout.

SLaks
Great, thanks a lot, this did it...
Prabhu
jQuery doesn't cache responses without headers for caching? Just curious, e.g. PHP doesn't send these headers by default
Znarkus
@Znarkus: This is an IE issue; IE has very aggressive caching.
SLaks
For some reason though passing the string to setTimeout works...
Prabhu
@Prabhu: It works, but it's bad practice. (It's much slower)
SLaks
@Prabhu: Passing the code as a string makes it eval it, which is something you should always avoid.@SLaks: Thanks, good to know.
Znarkus
@Prabhu: Also see my answer for a shorter and more jQuery-style approach.
Tomalak
Cool, thanks...
Prabhu
+2  A: 

jQuery's ajax has a bunch of default settings, one of which controls caching. If you set that to false it will append a timestamp to the ajax call to prevent caching.

http://api.jquery.com/jQuery.ajax/

Dan
+1 for suggesting $.ajax. I never use the shorthands, this is just easier to remember.
Znarkus
A: 

Is there a better way to do what I'm trying to do other than polling periodically?

Since HTTP is a stateless protocol, no. You have to poll to see what's going on on the server.

But there is a better way to implement the polling:

setInterval(function () {
  $("#mydiv").load(location.href + " #mydiv>*", {Timestamp: new Date()});
}, 3000);

Notes:

  • define an Interval instead of the Timeout,
  • pass an actual function to setInterval, not a string
  • use the data parameter of load() to pass in a cache breaker
Tomalak
Will setInterval start the first call after 3 seconds or will it start instantly? I needed the first one to happen instantly.
Prabhu
@Prabhu: But the "first load" is the browser page load itself. Then the loads happen very three seconds. There is no need to refresh the page right after it finished loading.
Tomalak
@Tomalak -- cool, makes sense
Prabhu