Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON breaking back button in Chrome, Reload Button in IE (Showing as naked data)

Before Anything: $.getJSON back button showing JSON return data not the page did not help, as well as https://groups.google.com/group/angular/browse_thread/thread/3787ad609c0beb77/eb1b57069dab9f63 did not and the internet too did not help.

Here's the issue:

I'm calling an url from within a page to get json data, which then gets rendered with jquery templating inside this same page.

Imagine we're on the page http://someurl.com/search and we're starting a request like this

$.ajax({
  url: '/searchthis', //important, this is NOT THE SAME URL
  cache: false,
  type: 'GET',
  headers: {
    "Accept": "application/json",
  },
  dataType: 'json'
  success: function(data) {
    doSomethingWithResults(data);
  }
});

The Rack response has the cache control header set to no cache:

Cache-Control:no-cache

Everything works fine, but if you leave the page for another page in Chrome and then press the back button, you will get shown naked JSON Data. The same behaviour is there when you hit the reload Button in IE8. Both work perfectly fine if you just press Enter on the url in the adress bar.

I'm not getting how I could fix this, because the Chrome guys won't do it (see http://code.google.com/p/chromium/issues/detail?id=108425)

It seems to me like misinterpretation on the browsers side, because it caches something it really should not (response Header) and it caches something under a wrong url (because the JSON request does not hit the same URL)

like image 733
Beat Richartz Avatar asked May 23 '12 08:05

Beat Richartz


2 Answers

The problem was actually Rails: Both Chrome and IE request the last response with no specific format, so Rails just takes the first response block, which happened to be json in my case. Putting the html block in front of the json block solved the issue.

respond_to do |format|
  format.html { ... } //important because the request comes with no specific format
  format.json { ... }
end
like image 86
Beat Richartz Avatar answered Oct 23 '22 11:10

Beat Richartz


I had the same problem with Chrome. My controller's method does have the format.html

respond_to do |format|
  format.html
  format.js
end

It seems that Chrome caches results, so I was able to fix this by adding a data entry to my ajax request, like so:

$.ajax({
   url: '/restful/path',
   data: { format: 'js' }, // This line here
   dataType: 'json'
});

or you can pass the format by attaching it to the end of the request, just make sure you have the (.:format) option in your route

$.ajax({
   url: '/restful/path.js',
   dataType: 'json'
});

Hope this helps someone

like image 24
Mirko Akov Avatar answered Oct 23 '22 11:10

Mirko Akov