- rails.js from http://github.com/rails/jquery-ujs
- jquery.js from http://code.jquery.com/jquery-1.4.2.js
- application.js having your custom javascript command
- Load them
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
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.
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
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
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 ajaxifiedIt should print a message and update the ajaxified id with the post title when the form is submitted!
alert("Ajax works!"); // prints an alert message
0 comments:
Post a Comment