javascript - How can I pass a variable to a partial that is loaded when user clicks on a div? -



javascript - How can I pass a variable to a partial that is loaded when user clicks on a div? -

i trying load partial when user clicks on div element. problem want pass variables partial , can't find way.

i have written next code:

<script> $(".conversation").click(function() { <% @conversationid = capture %> <%= javascript_tag "$(this).attr('id');" %> <% end %> $("#conversation").html("<%= escape_javascript(render(:partial => 'conversations/conversation_home', :locals =>{:conversation => conversation.find_by_id(@conversationid)} )) %>"); }); </script>

i attempting initialize varialbe (@conversationid) , utilize pass object want partial. when load page attempts load partial (why? did not click anywhere), , "undefined method `subject' nil:nilclass" because conversation nil. if replace @conversationid value conversation initialized correctly.

why partial rendered when load page, instead after click on div? , initialize @conversationid properly?

is there approach take?

anything between <% , %> gets evaluated when page loads. thats expected behavior , thats why partial beingness loaded on page load.

use ajax

i utilize ajax. how it.

in html (add div each conversation id)

<div class="conversation" data-conversation-url="<%= conversation_path(:id => 1) %>">get conversation</div>

in javascript (i set in separate file)

$(document).on('click', '.conversation', function() { $.get({ url: $(this).data('conversation-url'), success: function() { // here }, failure: function() { // here } }); });

in conversations_controller

def show @conversation = conversation.find(params[:id]) end

in views/conversations/show.js.erb

$("#conversation").html("<%= escape_javascript(render(:partial => 'conversation_home', :locals =>{:conversation => @conversation} )) %>");

this should trick.

please note assuming have route set conversation_path. also, sample code. have modify fit needs, add together error handling , may alter code based on version of jquery , rails using.

javascript jquery ruby-on-rails

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -