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
Can someone please show to properly solve this problem? I would really
apreciate it! thank you!
stack
2
stack
3
You cannot call Ruby code directly from client side. You have to send an
AJAX request to some controller for this purpose.
stack
4
Kashif Umair L. 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
stack
5
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
Ruby on Rails - AJAX 