Wednesday, May 20, 2009

Mind your Cache when AJAXing

When using AJAX if you use Servlets to process your request be careful that subsequent requests might look to the browser as if the previous request and hence it might not bother to make a call to the Web Service/ Servlet call again. The answer to this is to set the response header as being non-cacheable.

For Servlet call :
response.setHeader("Cache-Control","no-cache");//HTTP 1.1
response.setHeader("Pragma","no-cache");//HTTP 1.0
response.setDateHeader("Expires", 0); //prevents caching at the proxy server

For Web Service call :
<%//Forcing no cache so browser hits the AJAX urls everytime else it will cache and show old data
response.setHeader("Cache-Control", "no-store"); //HTTP 1.1

response.setHeader("Pragma", "no-cache"); //HTTP 1.0

response.setDateHeader("Expires", 0); //prevents caching at the proxy server
%>


W3C web site has more about these tags. So next time you are AJAXing around, mind your cache!!

No comments:

Post a Comment

Thank you for your feedback