Reputation: 9
I'm working on rails app and have stumbled upon stupid yet simple problem. I need to invoke ruby method by triggering javascript button. I have a controller called Book and I'm placing method inside BooksHelper. What I want to do is simply trigger the execution of this method by button click which would output the result on the same page, I don't want that method opening another page. I've checked couple possible solutions but can't make them work. None of those methods in example.html.erb actually work. I would like to get help on how to fix the problem. It only works if I wrap up in alert method, but that's not what I want. I want the output to be printed out in the actual page. So, how can I do it? I've read the http://guides.rubyonrails.org/working_with_javascript_in_rails.html but it doesnt answer my question, since I'm not looking for creating new pages with controller and routes, but rather executing a ruby method in order to see result on the same page. Thank you!
<%= button_to_function "Output", "alert('#{outputString}')" %>
----------------------------------------------------------------------------
#app/helpers/book_helper.rb
module BooksHelper
def outputString
"output"
end
end
-----------------------------------------------------
#app/controllers/books_controller.rb
class PagesController < ApplicationController
def outputString
end
end
------------------------------------------------------
#app/views/books/example.html.erb
<%= button_to_function "Print", "outputString" %>
<%= button_to "Print", :action => "outputString" %>
<input class="ok" onclick="outputString()" type="button" value="Print" />
Upvotes: 0
Views: 193
Reputation: 13106
The controller/helper method outputString
isn't available client-side once your templates are rendered.
button_to_function
is for calling javascript functions via button click. You cannot call server-side functions directly from a javascript button without making an AJAX request back to the server.
Upvotes: 1