Monday, March 12, 2007

Cached Ajax Response

On my project i have a nice Upload wizard. It allows a user to write file information while the file is uploading. This page uses Ajax calls in order to communicate with the server while the file is still uploading.

I had strange behaviour with this page...
Sometimes it worked and sometimes not...
While debugging i found out that if i upload the same file twice the second time fails.
After placing breakpoints i found that the Ajax requests that fail never reach the server side.
This fact gave me the idea that the response is being CACHED by the browser.

In order to prevent Ajax requests from being cached by the browser i put these lines in my code before writing the response:

Response.Clear();
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;
Response.ContentType = "text/plain";

This solved the problem entirly.

P.S. If you are asking for static data using Ajax you may want it to be cached on the client to shorten response time. In that case don't use this code.

blog comments powered by Disqus