1

I'm using the following code to get data via JS request on my search page

<%= link_to 'All', '/search?type=all', id: 'active', remote: true %>
<%= link_to 'Photographers', '/search?type=photographers', remote: true %>

It's all working fine and I'm getting data as expected. But when I click some other link and then hit back button (provided by browser) it's showing me the JS request data on a blank page instead of going back to search page.

Is there any workaround or fix to this?

in routes.rb

resources :search, only: [:index]

in search controller

def index
  // search processing

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

search/index.js.erb

$('#search-area').html("<%= j render partial: 'search_area' %>");

I'm using Rails 5.0 with Puma

Hassan Ahmed
  • 168
  • 2
  • 9
  • include your controller and routes to help us better understand your code – Nirajan Pokharel Aug 25 '16 at 13:18
  • @NirajanPokharel added – Hassan Ahmed Aug 25 '16 at 13:43
  • sounds like the back button is going back to the last previous request which was the AJAX request from your `remote: true` link. Odd. What server are you using? The standard rails dev server can only handle one request at a time which might account for this. Try using `puma` as a dev server and see if the issue perists – Killerpixler Aug 25 '16 at 14:06
  • Alternatively look at your `search.js` view file. Depending on your JS implementation you might just have an empty page with the search JS running. – Killerpixler Aug 25 '16 at 14:07
  • @Killerpixler updated post, I'm using Rails 5 with Puma – Hassan Ahmed Aug 25 '16 at 14:21

1 Answers1

0

As I thought. The back button goes to the last request which is the JS file. ALL it does is render a partial but since it doesn't have a base template to go from all you get is the search data from the partial.

The way I have gotten AJAX partials to work so far is to have a div tag (or anything with an ID really) in the .html.erb file. For instance from a project with a AJAX sortable table:

index.html.erb

...
<div class="card card-block" id="article-index">
    <%= render 'indextable' %>
</div>
...

index.js.erb

$("#article-index").html("<%= escape_javascript(render("indextable")) %>");

Both refernce a partial for the table data I want to render. The trick is here in the .js.erb file to use the syntax of setting the innerHTML to a rails escape_javascript(render..) call. That way back navigation will work from another page back to the search result page.

Give that a try and let me know if it did the trick. Odds are you will get the HTML template for the search result page rendered but without any data. AJAX generally won't work with the browser back button.

Killerpixler
  • 4,200
  • 11
  • 42
  • 82