Caching Data for AJAX with Javascript

Here’s a way to cache data on the client side, via javascript. This was tested on Firefox 3.6.3 on Ubuntu.

The idea is to convert your data into Javascript, and then load it with the SCRIPT tag. You then use the Expires HTTP header to tell the client how long to cache the data. Finally, you use some Javascript code to display the data.

I read that if you POST the page back to the server, the cache is invalidated, and code is reloaded. My browser isn’t doing this. GET, on the other hand, doesn’t clear the cache. So, the trick is to use AJAX to post data to the site.

This short example show how to do it.

data.js.php:

<?php
header("Expires: ".date('r',time()+10));
$randchar1 = chr(rand(65,90));
?>
data = '<?=$randchar1?>'

This creates a random character, stores it as data, and sets the document to expire 10 seconds into the future.

code.js:

function showdata()
{
  document.write(data)
}

This just displays the data.

test.html:

<html>
<head>
<script type="text/javascript" src="data.js.php"></script>
<script type="text/javascript" src="code.js"></script>
<script type="text/javascript">
showdata();
</script>
<p><a href="test.html">test</a></p>
<form methoc="post">
<input type="submit">
</form>

You can try the example here.

Now, load up test.html in your browser. (This must be installed on a server running PHP, and you must view the page through the server. i.e. http://localhost/test.html. Don’t just view the file.)

Now, start clicking the “test” link at the bottom of the page. You’ll see that the data stays the same for 10 seconds, and then changes value.

Try clicking the submit button to see if it causes the cache to expire. Mine didn’t.

Note – if your server has the wrong time, the cache behavior will either take too long, or not happen at all.