Forum: Ruby on Rails run simple method from Helper on button click

01b14fccb535f9f1b35e00669fe79a80?d=identicon&s=25 leo nike (stack)
on 2013-10-27 17:27
Greetings,
I'm new to rails and currently having couple problems about how to add
javascript functionality into rails.

I have a simple method in the helper and i want to run this code on
button click.

   ------------------------------------------------------------------
     module PagesHelper
         def show_message
            "simple output"
         end
    end

   ------------------------------------------------------------------

   this doesnt work
   <%= button_to_function "Print", "show_message()" %>

   this doesnt work too
   <input onclick=" show_message() " type="button" value="PRINT" />

Can someone please show to properly solve this problem? I would really
apreciate it! thank you!
1703a0c3ed358b787f4b1bf3b2799472?d=identicon&s=25 ZeroModulus (Guest)
on 2013-10-28 01:24
(Received via mailing list)
The `button_to_function` method's second argument should be JavaScript,
not
Ruby.

See:
http://api.rubyonrails.org/classes/ActionView/Help...
66e52919f143c02bb0b3df613f3a4553?d=identicon&s=25 Kashif Umair Liaqat (Guest)
on 2013-10-28 06:45
(Received via mailing list)
You cannot call Ruby code directly from client side. You have to send an
AJAX request to some controller for this purpose.
01b14fccb535f9f1b35e00669fe79a80?d=identicon&s=25 leo nike (stack)
on 2013-10-28 15:52
Kashif Umair Liaqat wrote in post #1125837:
> You cannot call Ruby code directly from client side. You have to send an
> AJAX request to some controller for this purpose.

How would I do that? I have no knowledge of AJAX
66e52919f143c02bb0b3df613f3a4553?d=identicon&s=25 Kashif Umair Liaqat (Guest)
on 2013-10-29 07:30
(Received via mailing list)
Suppose you have a controller HomeController. It should look like below.

home_controller.rb

class HomeController < ApplicationController
  # GET /show_message
  def show_message
    format.js { render js: "alert('simple output');" }
  endend

and in your routs.rb file add this line

get '/show_message', 'home#show_message', as: :show_message

and in your view add this line

<%= link_to "Print", show_message_path, remote: true %>

After this when you click on Print link, and AJAX request will be sent
to
HomeController'sshow_message action and it will display a javascript
alert.

For better understanding of AJAX requests in Rails, follow this tutorial
-
http://www.tutorialspoint.com/ruby-on-rails/rails-... :)
01b14fccb535f9f1b35e00669fe79a80?d=identicon&s=25 leo nike (stack)
on 2013-10-30 09:06
Thanks a lot!
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.