Q:

JQuery pagination in Rails causing render failures

I'm using JQuery to implement pagination in my rails app, and have run into a problem where sometimes rails fails to render the page content when I hit back in my browser, and instead it dumps the raw Javascript into my browser window. Here's a quick  look at what I'm using:
pagination.js:
if (history && history.pushState) {
  $(function () {
    $('.pagination a').live("click", function () {
      $.ajax({url: this.href, dataType: "script", cache: true});
      history.pushState(null, document.title, this.href);
      $("html, body").animate({ scrollTop: 0 }, 300);
      return false;
    });

    $(window).bind("popstate", function() {
      $.ajax({url: location.href, dataType: "script", cache: true});
    });
  });
}

And in my view, index.js.erb:
$("#products").html("<%= escape_javascript(render("products")) %>");

It works some of the time, but often when hitting the back button the JS is dumped into my browser window without being evaluated/rendered. It looks like this (in my browser):
$("#products").html("<table class=\"table table-striped\">\n<thead>\n<tr>\n<th>Products

...etc. I'm not sure exactly what is failing. Any ideas?

A:

The paths requested by your browser look like

/products
/products?page=1
/products?page=2

Depending on whether /products?page=2 was browsed to 'manually' or via ajax you render the js version or the plain version. When you hit the back button you may just get what is in the browser's cache which could be either of those two versions depending on what your previous navigation history was.
In order for this to work properly you want the browser to maintain two separate versions of the cache. One way of doing this is by adding an extra parameter when you make your ajax request:
$('.pagination a').live("click", function () {
  $.ajax({url: this.href, dataType: "script", cache: true, data: {'ajax_paginate': true});
  ...
});

jquery-pjax already does this, and if you use the pjax-rails plugin the magic cache-separating parameter will be stripped for you automatically.
You'll want to empty your browser cache before you try this out - you've probably already got a bunch of bad data in the cache.

