6

I have an application that displays a large number of informational pages based on a location that I store in the session variable.

I am using a single select in a partial shared between varied pages from other controllers.

_location_select.html.erb

<%= select_tag(:location, options_for_select(Location.all.order('name ASC').collect { |l| [l.name, l.id] }, [session[:location]||'']), include_blank: true) %>

This makes an ajax call to:

locations_controller.rb

class LocationsController < ApplicationController
  def select
    session[:location] = params[:value]
    render js: ''
  end
end

Here is my coffescript:

home.js.coffee

$ ->
  $('#location').change ->
    $.get '/location/select', {value: $('option:selected', this).val()}

All of this code works great, but I need to have the page reload after the ajax call is complete, It would be too complicated to have the controller return the updated html since the location select will appear on such a large number of pages.

I have tried adding success:, and error: call back functions to the ajax call and have also played around with ajaxStop. I can get the ajax call to work or the page reload to work but cannot figure out the way to get both.

I have tried adding:

$(document).ajaxStop(function(){
    window.location.reload();
});

Where do I put location.reload() or is there a better way?

FYI, I am not using turbolinks in this app.

1 Answer 1

15

locations_controller.rb

class LocationsController < ApplicationController
  def select
    session[:location] = params[:value]
    respond_to do |format|
        format.js   {}
    end
  end
end

views/locations/select.js

window.location.reload();
Sign up to request clarification or add additional context in comments.

3 Comments

So easy and so obvious, I am almost embarrassed to admit, that I did not try that first.
And at least in rails 4, I don't think the respond_to block is required - if select.js is the only select.* view file in the views/locations folder, it will get picked up automatically
it so hard to see the forest through the trees sometimes. simple and beautiful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.