简体   繁体   中英

Passing JavaScript variable to ruby-on-rails controller

How can I pass a variable (id) from the JavaScript listener:

Gmaps.map.callback = function() { 
    ...
    ...
    google.maps.event.addListener(marker, 'click', function() {
      var id = this.currentMarker;
      alert(id); 
    });
   }
  }

To the instance variable (@foo) in ruby-on-rails controller

def create
  @foo = ???
  ...
end

to correctly create a relationship in the view (form):

<%= form_for user.relationships.build(:followed_id => @foo.id) do |f|    %>
<div><%= f.hidden_field :followed_id %></div>
<div class="actions"><%= f.submit "Follow" %></div>
<% end %>

Thanks!

If I am understanding correctly, a good way to do this is to use AJAX to submit the id to your action and use the action to render your form.

That would look something like this in your javascript:

jQuery.ajax({
  data: 'id=' + id,
  dataType: 'script',
  type: 'post',
  url: "/controller/action"
});

You'll need a route:

post 'controller/action/:id' => 'controller#action'

Then in your action you can grab that id and render your form something like this:

def action
  @user = User.relationships.build(:followed_id => params[:id])
  render :viewname, :layout => false
end

Then you can just build a form for @user in a partial or whatever

<%= form_for @user do |f| %>

You'll have to fill in the details there, but that should get you pretty close.

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