1

I want to have a button that, when clicked, will execute rails code. Is javascript necessary for this? Is there some ruby-javascript (.js.rb)?

if button is clicked... execute A However i do not want to redirect or go to a new view, just ruby code to be executed.

1 Answer 1

3

Yes. Try googling unobtrusive javascript. With rails specifically the following is the general principle (rails v 3.0 or greater), and is most often used for forms.

Here is an example of using a remote form to post a "message" via javascript.

First setup your controller to respond to javascript. So for example a "create" action would look something like this:

def create
  @message = Message.new(params[:contestant])
  #do whatever you want
  respond_to do |format|
  if @contestant.save
     format.js
     format.html { redirect_to(@message, :notice => 'Message was successfully created.') }
  else
     #deal with errors here/ redirect wherever you want
  end

Now create a file called "create.js.erb". This follows the rails naming conventions for controller actions, but note the js.erb extension.

In this code you can put whatever javascript you want to respond with, and in rails 3.1 or you can use jquery by default as well.

$(#messageform).html("<h3>Thanks for sending your message we will be in touch shortly</h3>");

Then in your view that you want to initiate this javascript call you would put a form like this:

<div id="messageform">
  <%= form_for @message, :remote => true do |f| %>
    <h2>Send us a message</h2>
      <p>
        <%= f.label :email %>
        <%= f.text_field :email %>
      </p>
      <p>
        <%= f.label :message %>
        <%= f.text_area :message %>
      </p>
      <p>
        <%= f.submit "Send message!"%>
      </p>
   <% end %>
</div>

This is a standard form_for. Only thing special here to notice is the :remote => true parameter at the beginning.

Anyways hope this helps :)

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

3 Comments

Thanks, quick question though. Where do I put the create.js.erb?
in the views folder for your controller
if you have a messages_controller.rb, but the create.js.erb into view/messages directory

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.