0

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" />  

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So, this problem is only solved via AJAX? no other option? I have no knowledge of AJAX unfortunately, guess will have to learn it now..Thanks!
@user2928354, yep, you're looking at a remote procedure call. And yep, it uses AJAX.
Yes, look at it like the Rails code is server-side and the views are rendered and executed client-side. So when this html is sent down to the client (browser) and they click the button they are client-side, they dont have access to functions that only live on the server in server-side code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.