I'm generating a chart in Rails using a d3.js JSON callback like this:
View
d3.json(document.URL, function(data){ 
    // generate chart
}
Controller
def index
    respond_to do |format|
        format.html do
            # return the HTML
        end
        format.json do
            # return the JSON
        end
    end
end
All works fine. However when a user leaves this chart, and then navigates back to it using the "back" button on their brower they are presented with the JSON rather than the HTML.
Can you suggest how I might fix this?
Well, this is because when you hit back button the browser is serving last cached content for the given URL. IIn your case the last content is JSON requested by AJAX (D3).
In addition to accepted answer you can also try the other way - just append .html to page URL. You can automate it by adding this filter to controller or ApplicationController: 
   before_filter do
     if request.format == :html && !params[:format]
       redirect_to format: :html
     end
   end
There is also a third standard way with Vary: Accept header but it may cause some troubles because of this Chrome bug and some problems described in The browser cache is Vary broken
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With