Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hitting browser "back" button shows JSON rather than HTML (using Rails & d3.js)

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?

like image 684
Derek Hill Avatar asked Aug 15 '12 09:08

Derek Hill


Video Answer


1 Answers

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

like image 140
gertas Avatar answered Nov 15 '22 16:11

gertas