20 October 2013

Preventing Caching of Ajax Requests

Normally when we use Ajax calls using get method the Ajax request will be cached in the browser’s history and the html pages are cached in the browser’s cache. So the problem with this is, when user clicks on the back button of the browser to return to previous page which have some ajax calls then the calls gets fired but the response comes from the cache. It does not hit the server. If we want to prevent the caching we have to make every request unique by adding a request parameter with some unique value.

The following technique shows how to make request unique:- 

var nocache = new Date().getTime(); 
var path = 'http://hostname.domain.tld/api/somejsonapi/?cache=' + nocache;

Now use the path as your url so that the request becomes unique every time and will not return the cached response. 

If using Ajax calls with get is not mandatory then use Ajax with post method so that the ajax requests and responses are not cached. Post method prevents caching in Ajax.

Post a Comment