Written by: steve ross on April 27th 2008

Today I posted a couple of simple jQuery plugins on github. They are:

jquery.focus_first.js
jquery.rails_ajax_hook.js

You can clone them by doing:


git clone git://github.com/sxross/jquery_plugins.git
  

The first one simply sets the focus on the first INPUT element in a form, if such a form exists. Usage:


$(document).ready(function(){
  $(this).focusFirstInput();
}
  

That's it!

The second, ajaxLinkBind, is more complicated. Its purpose is to bind to an 'a' element and invoke some Ajax action in a Rails controller. Here's how it works.

(X)HTML


    
hey click here.

Clearly, this is just a thing that links using an HTTP GET request, right? But add the following Javascript and this plugin:


    $('.linkable-by-ajax').ajaxLinkBind(
      {
        success: function(json){
          $('#update-me').html(json['results']);
        }
      }
    )
  

...and presto! You have Ajax. The GET is replaced by an Ajax POST with an Accept-Type of Application/json, and the response is interpreted as JSON. Because the options hash maps directly onto the options hash of $.ajax(), you can use any of the options available, although I would recommend constraining yourself to dealing with success and error. Additionally, because this is designed to decay gracefully into an HTTP GET if Javascript is not enabled, stuffing things into data is a "really bad idea."

Finally, a word about your Rails controller. Use a snippet like this:


    def my_method
      respond_to do |wants|
        # Expected case, the Ajax request. Just set the JSON variable "results" and let the Javascript render it.
        wants.json {
          render :json => {:results => 'the magic number is 42!'}
        }
        # Downlevel result where browser Javascript is turned off. Set the flash to our message and go back
        # whence we came.
        wants.html {
          flash['info'] = 'the magic number is 42!'
          redirect_to request.referer
        }
      end
    end