Blog

Cache Busting in your JQuery ajax calls

Posted by Mike Gold Blogs | ASP.NET MVC May 17, 2009
One of the problems I've run into in designing websites is that the URL of the websites are cached by the browser and this causes the information in the page to remain stale. In order to force the web page to refresh, you need to trick the browser. Here is how.

In working with a QA team when creating Ajax calls to my  MVC controllers, I've had to deal with the nagging problem of caching.  This problem is particularly true with IE, because IE turns caching on by default.    The problem is, that when you start to develop an application where data in a databases is changing.  If you have caching on,  the page shows ancient data that does not reflect the data in the database.

The problem occurs because the browser uses the URL as a key, and caches the associated page data with this key.  If the key doesn't change, then the page doesn't change.  Caching was created as a "convenience" to load the page quickly if the URL was already visited.   To me, the developer,  it's more of a nuisance.

So you need to refer to something called cache busting to prevent the browser from showing stale data.  Cache busting tricks the browser into thinking that there is a new URL everytime.  To do this, you can pass an extra random parameter on your URL string that changes every time your page comes up or you can use the built in functionality for cache busting in JQuery which essentially does the same thing.

Here as an example of calling an AJAX call (through JQuery) to retrieve page info from an MVC controller using cache busting.

Here is the manual method for cache busting that generates a random parameter
using javascript.

(for JQuery 1.2.6)
$.ajax({
type: "GET",
url: "http://domain.com/Account/GetProduct?productId=5&r=Math.random()",
success: function(){}
});

And here is the built in method in JQuery for cache busting:

(I believe this works for JQuery version 1.3.2 and on)
$.ajax({
type: "GET",
url: "http://domain.com/Account/GetProduct?productId=5",
success: function(){},
cache: false
});


Here is what the controller would look like on the server side (with default MVC routing)




public class AccountController
{
public JsonResult GetProduct(int? productId)
{
return Json(GetProductFromDB(productId));
}








}











PREMIUM SPONSORS
Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.
Employers - Post Free Jobs
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.