Ajax and browser 'back' button

Hi

I’m trying to find a solution to what I would describe as
inconsistent state of session objects updated from multiple pages
using Ajax techniques.

A concrete example would help.

The ‘Agile Web D. with Rails’ book includes the development
of a sample application called the Depot application. Its a shopping
application - where the user shops for books, places them in a ‘cart’,
and ultimately ‘checks out’.

The Depot application has a page where you can see all the available
books - along the left-nav there’s also a summary of the users
‘cart’. Every time a user adds a book to their cart - the left-nav
summary is updated accordingly. In addition - assume there’s a link
on this page - let’s call it the ‘shopping’ page, that allows a user
to go to another page and edit the contents of their cart - let’s call
that page the ‘edit cart’ page.

Imagine a user has added 4 books on the ‘shopping’ page, then they go
to the ‘edit cart’ page and delete all the items from their cart -
books are removed from the ‘cart object’ every time the user deletes a
book from their cart. The cart object is stored in the session. They
then hit the browser’s ‘back’ button - taking them back to the
‘shopping’ page - which shows the cart containing 4 books in the left-
nav summary - the same books that were in the cart when the user
initially left the ‘shopping’ page. If the user refreshes the
‘shopping’ page - the cart is now empty, correctly reflecting the
contents of the cart.

I found what appears to be a solution that works ‘sometimes’. I
don’t mean to be imprecise - but it literally works sometimes in
production mode and sometimes not. I have no idea why.

The fix can be explained here …

http://giantrobots.thoughtbot.com/2008/4/25/pitfalls-in-restful-wizards

and amounts to adding a ‘filter’ which calls a private ‘no_cache’
method defined in application.rb …

def no_cache
response.headers[“Last-Modified”] = Time.now.httpdate
response.headers[“Expires”] = 0

# HTTP 1.0
response.headers["Pragma"] = "no-cache"

# HTTP 1.1 'pre-check=0, post-check=0' (IE specific)
response.headers["Cache-Control"] = 'no-store, no-cache, must-

revalidate, max-age=0, pre-check=0, post-check=0’
end

I then added the following line to the controller/actions that I want
to not be cached …

after_filter :no_cache, :only => [:index]

Note: the link I included above uses a ‘before’ filter, and in my
testing that didn’t seem to work - but an ‘after’ filter did.

Now - like I said above, it works sometimes, other times not. So my
question - does anyone know why ?

Additionally - is there a reliable browser agnostic fix that can
address the underlying issue - specifically, force pages that users
return to when hitting the browse button to not be cached and actually
request the page from the server?

Any help would be greatly appreciated. Thanks for making it this far
and sorry for the length of the post.

Dave