Sunday, 18 February 2018

Ajax reqeuts getting cached in IE and Firefox

Usecase: Debug ajax cache issues in IE and Firefox.

Issue: Ajax requests return wrong or same data in IE and Firefox, since the requests get cached in the browser. Requests work for the first time, from next time browser will give the same result.

Root Cause: When a GET request is made to a web service, IE will automatically cache the responses from GET requests. Once IE has successfully made a GET request, it will no longer make a new AJAX call until the cache expires on that object.

Solutions:

  1. Use POST: Use POST requests instead of GET requests in your application. However, this is bad practise, simply because POST requests should only be used when you are submitting data or modifying a resource on the server.
  2. Response Headers: You can prevent caching by sending additional headers along with your response. By specifying the “Cache-Control” header with a value of “no-cache,no-store” and returning it with the web service response you can instruct the browser not to cache the result. For example in C#:HttpContext.Current.Response.AddHeader("Cache-Control","no-cache,no-store");
  3. Cache Buster: A cache-buster is a dynamic parameter that you append to a request which makes each request unique, most commonly a random number or the current date/time ticks.
    1. var url = '/get/userDetails?buster='+new Date().getTime();
  4. Disable Cache for JQuery AJAX Request:  If you’re using JQuery to perform your Ajax requests, you can add cache: false to the parameter list like so:
$.ajax({
    url: url,
    cache: false,
    dataType: 'json',
    type: "GET",
    data: data,
    success: func,
    error: ajaxError
});
If you want to globally setup cache for all JQuery AJAX requests use below code.
$.ajaxSetup({ cache: false });