Search code examples
ajaxcachingprototypejs

Why caching ajax request is not working?


I have a large json data object (over 300K uncompressed, 40K gzipped) which is used on every page of my internal system. I want to fetch it every 15 minutes. In this time user will probably visit tens of pages of my system.

The HTTP Response headers in Firebug look like:

Cache-Control   max-age=899, public
Connection  Keep-Alive
Content-Encoding    gzip
Content-Length  44017
Content-Type    text/html; charset=iso-8859-2
Date    Tue, 04 Dec 2012 16:21:45 GMT
Expires Tue, 04 Dec 12 17:36:45 +0100
Keep-Alive  timeout=15, max=99
Last-Modified   Tue, 04 Dec 12 17:21:45 +0100
Pragma  no-cache
Server  Apache
Set-Cookie  user_auth=xxx; expires=Wed, 12-Dec-2012 16:21:45 GMT; path=/; domain=example.com 
Vary    Accept-Encoding
X-Genaration-Time   0.13282179832458 sec.
X-Genarator vCRM 3.1 (c) Veracomp S.A.
X-Powered-By    PHP/5.3.3-7+squeeze14

The cache headers are set to 15 minutes in future, but neither Chrome nor Firefox caches it. The Firebug says this about cache:

Data Size   44017
Device  disk
Expires Thu Jan 01 1970 01:00:00 GMT+0100
Fetch Count 5
Last Fetched    Tue Dec 04 2012 17:21:45 GMT+0100
Last Modified   Tue Dec 04 2012 17:21:45 GMT+0100

It seams the Expires header is ignored, but why?

This sould not mattery, but I better write, that the content type is text/html, so the server can gzip it, but in reality the content is JSON.

I am using Prototype.js to request this. I set the request header:

Cache-control: max-age=900

Prototype.js does not add any cache buster parameter to the url. I am using PHP with Zend_Framework to set serve the response.

What am I doing wrong?


Solution

  • Problem solved.

    As @Victor pointed out, I had the "Pragma: no-cache" header set. The header was somehow set by PHP. I worked with our webserver admin and we had managed to unset the header with Apache.
    Still it was not enough. Our framework sets cookies with every page refresh and I could not turn it of. Browsers did not want to cache the requests which set cookies. We had to unset the Set-Cookie headers too. Finally this two unsets allowed us to enable cache:

    <LocationMatch "(?i)/url/we/want/to/be/cached/.+">
           Header unset Pragma
           Header unset Set-Cookie
    </LocationMatch>