jQuery and Ajax in Rails 2.0
Posted: January 12th, 2008 | Author: Andy | Filed under: jquery, rails | No Comments »I’m having loads of fun with jQuery of late. Its small size and increasing collection of plugins has made me want to throw it in any app that has a need for javascript and ajax controls. So I thought I would just put down the basics for anybody wanting to give it a bash.
In this example I will be avoiding RJS and helper methods, sticking to writing pure Javascript. Plus as jQuery and jQuery UI is, in my opinion, rather cleaner and easier to read than Prototype and script.acul.us, RJS and helper methods would just gets in the way.
First thing is first, load up your javascripts including jQuery in your layout.
Lets make a standard link in a view that we are going to attach our jQuery magic to.
In our application.js we are going to convert this regular joe soap html link into an ajax one unobtrusively. Here is a good place to start having a read through the jQuery docs.
$function
$".ajaxLink"click function
$ajax
url: thishref
dataType: "script"
xhrsetRequestHeader"Accept""text/javascript";
;
return false;
;
;
Create our action in our foods controller that will spit out the food that foxes love to eat.
@food = 'foxes love chunky Bacon'
respond_to do |format|
format.js {} # renders fox.js.html
format.html {render :text => @food }
end
end
This method will respond to an Ajax request by rendering fox.js.erb, however, if the user‚Äôs browser doesn’t have javascript enabled we will just render the food string, this could easily be fox.html.erb.
Create our javascript ‚view‚ called fox.js.erb. We will just have an alert box for now, but this could easily be any other javascript method.
alert'<%= @food %>';
As you can see this is a fairly trivial example, but works rather well. Now if I wanted to Ajaxify any link, all I need do is give it the class .ajaxLink in the html. Much much cleaner than the onclick links the link_to_remote produced.