Thursday, March 25, 2010

JQuery and Unobtrusive Javascript on Rails 3

In the earlier post, JQuery on Rails 3. You will need a few files to kick start in using JQuery.
  1. rails.js from http://github.com/rails/jquery-ujs
  2. jquery.js from http://code.jquery.com/jquery-1.4.2.js
  3. application.js having your custom javascript command
  4. Load them in the layout file
Lets try adding an ajax link somewhere on a page. Notice the difference, we are no longer using link_to_remote anymore. We will instead be using link_to, passing in the :remote key.
index.html.erb

<span id=\"ajax_button\"><%= link_to \'ajax!\', \'/\', :remote => true %></span>

<div id =\'ajax\'>
</div>

What Rails 3 gives us in doing this. If you take a look at the html source file, we get a clean ajax request link in line with html5.

Then we will throw in some trivial JQuery codes into a generic application.js file. We will specify the span id of ajax_button to change the html content of a div id of ajax to have "lol" when the link is clicked.
application.js
$(document).ready(function(){
$("#ajax_button").click(function(){
$("#ajax").html("lol");
});
});


When done right, we should see an update on div id ajax.

In the next example, we are going to do some ajax together with Rails controller request.

For this example, a controller file, posts_controller.rb. We will add a format.js under the respond_to so the method knows that it should format a javascript file.

def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
#format.xml { render :xml => @post, :status => :created, :location => @post }
format.js
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
end


Then the same is true for forms in Rails 3, when we wanna send an ajax request, the remote_form_for has been scrapped and we will use form_for(@post, :remote => true), again passing in the remote key.
new.html.erb

<% form_for(@post, :remote => true) do |f| %>
<%= f.error_messages %>

<div class=\"field\">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class=\"actions\">
<%= f.submit %>
</div>
<% end %>

Then we will create another file in the View folder, create.js.erb which holds the JQuery logic that we want it to run when the create method is fired.
create.js.erb
$("#ajaxified").html(""); // updates the div id ajaxified
alert("Ajax works!"); // prints an alert message
It should print a message and update the ajaxified id with the post title when the form is submitted!

0 comments:

Post a Comment