Skip to content Skip to sidebar Skip to footer

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 How

Solution 1:

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:

defcreate@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 wantend

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

Post a Comment for "Js Buttons To Execute Rails Code"