Wednesday, July 01, 2009

Ajax :- XMLHttpRequest response bypassing the Cache

It's possible that an XMLHttpRequest response will be cached by the browser. Sometimes, that's what you want and sometimes it's not, so you need to exert some control over caching.

With cache control, we're talking about "GET" based requests. Use "GET" for read-only queries and other request types for operations that affect server state. If you use "POST" to get information, that information won't be cached. Likewise, if you use "GET" to change state, you run the risk that the call won't always reach the server, because the browser will cache the call locally.

How to bypass the Cache:-

Often, you want to suppress caching in order to get the latest server information, in which case a few techniques are relevant. Since browsers and servers vary in their behaviour, the standard advice is spread the net as wide as possible, by combining all of these techniques
  • You can add a header to the request: xhReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
  • You can make the URL unique by appending a timestamp var url = "sum.phtml?figure1=5&figure2=1&timestamp=" + new Date().getTime();
Caching is sometimes a good thing when the service is time-consuming to call and when it's unlikely to have changed recently. To encourage caching, you can adjust the above advice, i.e. set the "If-Modified-Since" and "Expires" headers to a suitable time in the future. In addition, a good approach for smaller data is to cache it yourself, using a Javascript data structure. Browser-Side Cache explains how.

No comments: