user1002563
user1002563

Reputation: 335

Set a Rails/Ruby variable using Javascript via Ajax

In my nav-list, I have a drop box selection that contains all users, exclusively available to an administrator. The administrator can select a user, and the view is updated via ajax to display the selected user's information.

The view is updated with something like this:

$(#Users).change(function() {
    $ajax({
        ... yada yada update information in view.

However, what I want to implement is if I change to another view/url (Such as my account html.erb to a mygraph.html.erb) or refresh my page, I want the user drop box selection to persist with the user selection I made.

I thought of using rails cookies to do this. But I must redirect to controller to set the cookie.

I attempted a POST ajax call,

$(#Users).change(function() {
  $.ajax({
    ...
    data: {
       "<%= cookies[:selected] %>": this.value

It doesn't work, but for some reason, I already doubted that it would be that simple.

How should I implement this solution?

Upvotes: 2

Views: 1961

Answers (1)

Rahul Tapali
Rahul Tapali

Reputation: 10147

You don't have to redirect_to controller action. You can make ajax call to controller action. You can set cookie in controller action as follow:

 $(function(){
   $('#user_select')change(function(){
     value = $(this).val()
     $.post("controller/action",{selected_value : value}, function(data, status){
       if(status == "success")
       {
         alert(data);
       } 
    });
   return false;
   })
  })

Controller:

 def action
   cookies[:name]=params[:selected_value]
   render :text => "success"
 end 

Upvotes: 4

Related Questions