Written by: steve ross on April 27th 2008

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


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:


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.


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:

        success: function(json){

...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