简体   繁体   中英

Pass value of selected country (dropdown) in session and then reload current page (Rails 4)

In my Rails app, I'm trying to ask the user in the footer which country he'd like to see (France/United States/Germany...) and then store this in session and reload the page he's currently on.

Note that: I just want the current page to reload but I don't want to add a params in the URLs of my app(ie I don't want example.com/browser_country=France). I want them to stay as they are (example.com).

How can I do that?

This is my code below but it's not working (i'm a Rails newbie):

<footer class="footer">

    <small>
        MySuper Website <br/>
        <select name= "browser_country", :onchange => "location.href = '#{current_path}'"  >
           <option value="">Select Country</option>
              <option value="1">France</option>
              <option value="2">United States</option>
        </select>

    </small>

Here if the controller that loads the page (homepage)on /app/controllers/static_pages_controller.rb

class StaticPagesController < ApplicationController

  def home        
  end

  def set_country_into_session
    session[:country] = :browser_country # i'm putting in session the country selected in the dropdown
  end       

end

You will need to add an ajax call to this process.

# your js file
$(function() {
    $('select[name="browser_country"]').change(function() {
        $.ajax({
            url: 'static_pages/set_country_into_session',
            data: 'browser_country=' + this.value,
            success: function() {
                location.reload();
            }
        });
    });
});

# static_pages_controller.rb
def set_country_into_session
  session[:country] = params[:browser_country]

  render text => :ok
end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM