简体   繁体   中英

JS buttons to execute rails code

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM