If you're using a more recent version of Rails, and wanted to do this in an unobtrusive fashion as possible, you'd use the :respond_to options in your controller, like so:
class MyController < ApplicationController
def first_method
respond_to do |format|
format.html # this handles normal requests asking for html
format.js # this handles requests asking for javascript to be sent instead
end
end
end
If you're responding to a click, you'd do something like firing the query like so on the page
$("a.element_you_click_to_trigger").click(function(e) {
e.preventDefault(); // make sure clicking doesn't trigger unneeded event bubbling
$.ajax({url: "/controller/first_method", type: "POST", dataType: "script"}); // send a request and tell the server that you want javascript back
}
Just like you have an index.html.erb file in your views folder for that controller, you'd have a similar first_method.js.erb
file in relevant views folder along side
your index.html.erb
file:
views
controller
index.html.erb
first_method.js.erb
This will return javascript that gets executed client side, but it gets build server side, so you can contain rails ERB fragments, so you can do something like this:
$('#loading_placeholder_element').html('<%= escape_javascript(render(:partial => "create")) %>');
// do some other stuff you fancy in the page
// then make the next call once the other stuff is over (you may need to add this as a call back on an animation):
$.ajax({url: "/controller/second_method", type: "POST", dataType: "script"});
You'd then repeat the same process again for each of the others longer methods that fsmf highlighted.
I found this Railscast on jQuery incredibly helpful when I was learning this a couple of months ago, and I'd really recommend it.
Hope this helps !