Unobtrusive JavaScript in Rails 3

June 8th, 2010 at 1:40 pm • permalink58 comments

This article targets Rails 3

The article was written as of Rails 3.0. The information contained in this page might not apply to different versions.

One of the biggest changes on the frontend side of the upcoming Rails 3 version is the replacement of the Prototype JavaScript helpers in favor of Unobtrusive JavaScript (UJS). The implementation of Unobtrusive JavaScript, and the consequent removal of the old inline AJAX commands, offers at least three advantages:

  • Less verbose, inline, behavior code in the HTML document, with the result of much more lightweight, cleaner and readable source code
  • Rails 3 is no longer Prototype-oriented. With Rails 3 you can easily switch from a JavaScript framework to an other.
  • Rails 3 code is now JavaScript framework agnostic. It no longer contains framework-specific commands or scripts.

Let’s jump right into an example. Do you remember the link to destroy an object, generated by the link_to helper?

<%= link_to "delete", domain_path(@domain), :method => :delete, :confirm => "Are you sure?" %>

outputs

<a href="/domains/1" class="destroy" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'pKvg9hsnQ33uk='); f.appendChild(s);f.submit(); };return false;">delete</a>

The same Ruby helper call, in Rails 3, generates

<a href="/domains/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">delete</a>

This is made possible by the use of Unobtrusive JavaScript. The entire logic to handle the emulation of the HTTP DELETE method has been extracted into a separate JavaScript file and is executed when the page is loaded. The scripts containing the behavior are then attached to their corresponding JavaScript events. We’ll take a closer look at that file in a few minutes.

This feature required a major rewrite of the ActionView helpers which resulted in the following changes:

  1. New helpers and files are available to add unobtrusive JavaScript support to your Rails application
  2. The ActionView::Helpers::PrototypeHelper has been heavily modified. Many legacy helpers are now available as a separate plugin
  3. All the remote_<method< helpers has been removed. To make them working with AJAX, simply pass the :remote => true option to the original non-remote method
  4. All the AJAX-specific options representing callbacks are gone. For instance, there’s no :loaded, :loading or :complete option for remote link_to helper anymore.

So what?

At this point, you might be wondering what this means in practice and what you need to change in order to make your Rails 2 application working with Rails 3.

So let’s go back to the list of changes and discuss each point in the list. I’m assuming you will use the jQuery framework, but the same principles can apply to all the other supported JavaScript frameworks.

1. New helpers and files

The heart of the Unobtrusive JavaScript feature in Rails 3 is the new rails.js file. When you generate a new Rails 3 application, a file called rails.js is created in the public/javascripts folder along with all the other .js files you are used to see in a Rails 2 project.

rails.js contains all the unobtrusive handlers. By default, Rails assumes you are using Prototype, but there’s also an official fork for jQuery.

You need to include this file in your application to have all the unobtrusive features working correctly. Because rails.js is part of the :defaults bundle, if you are using the following statement you don’t need to change anything.

<%= javascript_include_tag :defaults %>

Otherwise, you can include the files separately. This is the case, when you want a more fine-grained control over the scripts included in your application or you want to use other alternatives, such as a CDN.

<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "jquery.rails.js", "application.js" %>

Now we know about the files, but what about the helpers? If you ever worked with remote helpers in Rails 2, you are probably aware of the Rails authentication token. In Rails 3, the authentication token still exists, but it needs an unobtrusive touch.

Here comes the new csrf_meta_tag helper. It returns two HTML meta tags which include all the information necessary to support the XSS protection in Rails 3.

<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="9SdBB/Uftw7IDQH4aKblEUcLXwvgw9vkju9N1ObyCCM="/>

Because the output is meta tags, this helper is expected to be called in the head section of your HTML page. In all likelihood, this will happen in your Rails layout files.

Here’s the simplest Rails 3 layout

<!DOCTYPE html>
<html>
<head>
  <title>Foo</title>
  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
</head>
<body>

<%= yield %>

</body>
</html>

As you can guess from the DOCTYPE declaration, the new default Rails layout is a HTML 5 document. Get yourself accustomed to it, unobtrusive JavaScript and HTML 5 are very good friends.

2. ActionView::Helpers::PrototypeHelper

ActionView::Helpers::PrototypeHelper has been heavily modified. The following helpers have been removed and made available as a plugin.

  • button_to_remote
  • submit_to_remote
  • observe_field
  • observe_form
  • periodically_call_remote
  • link_to_remote (*)
  • form_remote_tag (*)
  • form_remote_for (*)
  • remote_form_for (*)

(*) partially supported using the :remote => true option. See section 3.

If you are using one of these tags, you might need to rewrite the logic using Unobtrusive JavaScript.

Here’s an example for the observe_field helper, using jQuery. When the content of the field is changed, the browser triggers a call to the :live_search action and replaces the content of the #results element.

<%= text_field_tag :search %>
<%= observe_field :search, :url => live_search_path, :update => :results %>

In Rails 3 becomes

// Append the function to the "document ready" chain
jQuery(function($) {
  // when the #search field changes
  $("#search").change(function() {
    // make a POST call and replace the content
    $.post(<%= live_search_path %>, function(data) {
      $("#results").html(data);
    });
  });
})

The example above uses at least 3 different jQuery methods: $(document).ready(), .change(), and jQuery.post.

One additional note about the example. Placing a javascript_tag in the middle of a page is probably not so unobtrusive. I suggest you to take advantage of the content_for helper to dynamically inject the content in the head section of your page, or place all the login in a separate JavaScript file, such as application.js.

As you probably noticed, Rails 3 forces developers to have a deeper understanding of JavaScript. You gain flexibility for the price of additional development effort. From one side, this requirement makes Rails development less automatic, unlike it has been until today. From an other point of view, this requirement makes developers more aware of what they are doing.

If you are using Prototype, you might be tempted to install the legacy plugin. Don’t do it. Even if it makes Rails 3 upgrade easier, you would probably continue to use legacy helpers and your application will become harder to upgrade day after day. Taking the faster and easier way is not a good idea in the long terms. Schedule a reasonable amount of time and plan the full upgrade instead.

I believe this change would encounter many disappointed developers as soon as Rails 3 will be largely available, but I’m sure it will eventually become one of the most appreciate design decision in the long term. I strongly agree with the Rails 3 development team for this choice. It also comes at the right time. If Rails 1 or Rails 2 wouldn’t have included such easy way to write JavaScript from the beginning, many existing Rails developers would probably never been captured by the framework in the past.

3. remote_<method> helpers

As mentioned in the previous section, all remote_something and something_to_remote methods have been removed from Rails 3. Nonetheless, remote helpers are still available thanks to the :remote => true option.

Here’s a few examples.

# Rails 2
link_to_remote "Name", url_path
# Rals 3
link_to "Name", url_path, :remote => true

# Rails 2
form_tag "/path" do
end
# Rails 3
form_tag "/path", :remote => true do
end

# Rails 2
remote_form_for @article do
end
# Rails 3
form_for @article, :remote => true do
end

Rails 3 helpers never write inline JavaScript. Instead, they use HTML 5 data attributes to store remote metadata information within the HTML element. The rails.js file contains all the behavior required to handle these attributes.

Let’s use the link_to helper as example.

<%= link_to "destroy", article_path(@article), :method => :delete, :remote => true %>

The output is

<a href="/articles/1" data-method="delete" data-remote="true" rel="nofollow">destroy</a>

Notice the data-method and data-remote attributes. The first indicates you want to perform a DELETE HTTP request. The second identifies a remote request and is added whenever you use the :remote option.

<%= link_to "destroy", article_path(@article) %>
<a href="/articles/1" rel="nofollow">destroy</a>

<%= link_to "destroy", article_path(@article), :method => :delete %>
<a href="/articles/1" data-remote="true" rel="nofollow">destroy</a>

<%= link_to "destroy", article_path(@article), :remote => true %>
<a href="/articles/1" data-remote="true" rel="nofollow">destroy</a>

If you open the rails.js file, you will notice several remote handler definitions. The first one handles the case of remote form submission, the second one handles remote links and input fields, the third handles not-remote links that should behave likes form.

/**
 * remote handlers
 */
$('form[data-remote]').live('submit', function(e) {
  $(this).callRemote();
  e.preventDefault();
});

$('a[data-remote],input[data-remote]').live('click', function(e) {
  $(this).callRemote();
  e.preventDefault();
});

$('a[data-method]:not([data-remote])').live('click', function(e) {
  // ...
});

I strongly encourage you to carefully examine the content of the rails.js file before actually starting with the upgrade. As I said before, this is the center of the Rails 3 unobtrusive feature and you MUST have a good understanding of it.

Ryan Bates also created a very good screencast about upgrading remote helpers to Rails 3.

Reserved data attributes

From the rails.js file we can also extract the list of data- attributes which have a special meaning in Rails 3 and should therefore be considered reserved keys.

  • data-method
  • data-confirm
  • data-remote
  • data-disable-with

As a bonus feature, you don’t a Rails helper to take advantage of them. For instance, the following example will cause a confirmation dialog to appear when the button is clicked.

<button data-confirm="Do you really want to continue?">Click me</button>

4. Remote JavaScript callbacks

One topic I have never found covered so far in all the existing Unobtrusive JavaScript Rails 3 posts is remote JavaScript callbacks. This is odd because they are largely used. More precisely, I’m talking about the :loading, :loaded, :success, etc callbacks.

Quoting the link_to_remote Rails 2 documentation

The callbacks that may be specified are (in order):

:loading: Called when the remote document is being loaded with data by the browser.
:loaded: Called when the browser has finished loading the remote document.
:interactive: Called when the user can interact with the remote document, even though it
has not finished loading.
:success: Called when the XMLHttpRequest is completed, and the HTTP status code is in
the 2XX range.
:failure: Called when the XMLHttpRequest is completed, and the HTTP status code is
not in the 2XX range.
:complete: Called when the XMLHttpRequest is complete (fires after success/failure if
they are present).

You can further refine :success and :failure by adding additional callbacks for specific status codes.

Example:

    # Generates: <a href="#" onclick="new Ajax.Request('/testing/action', {asynchronous:true, evalScripts:true,
    #            on404:function(request){alert('Not found...? Wrong URL...?')},
    #            onFailure:function(request){alert('HTTP Error ' + request.status + '!')}}); return false;">hello</a>
    link_to_remote word,
      :url => { :action => "action" },
      404 => "alert('Not found...? Wrong URL...?')",
      :failure => "alert('HTTP Error ' + request.status + '!')"

A status code callback overrides the success/failure handlers if present.

These callbacks have not disappeared in Rails 3. It turns out they are now available as framework-native JavaScript events.

To better understand this point, we need to open the rails.js file again. Remember, for the purpose of this article I’m still referring to the official jQuery version.

Locate the callRemote function and search for the following lines:

beforeSend: function (xhr) {
  el.trigger('ajax:loading', xhr);
},
success: function (data, status, xhr) {
  el.trigger('ajax:success', [data, status, xhr]);
},
complete: function (xhr) {
  el.trigger('ajax:complete', xhr);
},
error: function (xhr, status, error) {
  el.trigger('ajax:failure', [xhr, status, error]);
}

Here they are, our lovely callbacks. They are now implemented as jQuery events:

  1. ajax:loading – triggered before executing the AJAX request
  2. ajax:success – triggered after a successful AJAX request
  3. ajax:complete – triggered after the AJAX request is complete, regardless the status of the response
  4. ajax:failure – triggered after a failed AJAX request, as opposite to ajax:success

If you are barely familiar with the jQuery.ajax() method, you already noticed that these custom Rails callbacks are very close to the original jQuery AJAX callback functions.

At this point, you are probably expecting a real example. I don’t want to disappoint you, so here it is, directly from this site.

We have the following Rails 2 form, which needs to show/hide a loading spinner to indicate the execution of the AJAX request.

<% form_remote_tag :url => { :action => 'run' },
            :id => "tool-form",
            :update => { :success => "response", :failure => "error" },
            :loading => "$('#loading').toggle()", :complete => "$('#loading').toggle()" %>

Of course, there are several different ways to accomplish this task and if I would go back, I would probably use a different jQuery-oriented alternative, but in the past it was dead simple to add such callbacks using Rails so let’s just upgrade the existing implementation to work with Rails 3.

First, remove all Rails 2 stuff and add the Rails 3 :remote option.

<% form_tag url_for(:action => "run"), :id => "tool-form", :remote => true do %>

Then, bind the function to toggle the spinner visibility to the appropriate AJAX events. Also, on success replace the content of #response with the response data.

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#tool-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(event, data, status, xhr) {
      $("#response").html(data);
    });
});

Remember

The upgrade to Rails 3 can be a bit more complicated if you heavily relied on Rails JavaScript generators in the past, but the benefits of switching to the Unobtrusive JavaScript patterns is definitely worth the effort.

Rails 3 forces developers to have a deeper JavaScript knowledge than in the past. Don’t underestimate the importance of this task, it’s an excellent chance to learn something more about the most important programming language today.

I hope this article will help you migrating upgrading your application to Rails 3.

Filed in Programming • Tags: , , , , ,

Comments

lg1046 says:

very a nice artice
thank you

Dennis says:

Thank you for taking the time to write this comprehensive article, much appreciated!

Thanks Dennis.

Following your profile link I just discovered iOctopus.
That’s amazing!

Reggie says:

Great articole Simone!
I liked it a lot… now lets go into the new Rails 3 world !

Hi Andrea, thanks for stopping by!

I have been waiting for you to connect on Gtalk since a few weeks!
I wanted to send you my congratulations for your project http://bit.ly/brjANL ;)

[...] Unobtrusive javascript in rails 3 Railscast – Unobtrusive javascript jQuery and Rails 3 Filed under: GeekKeith Get notified of new posts! [...]

cowboycoded says:

Great tutorial! It is definitely the best on UJS in Rails 3 that I have seen. Info on callbacks is what I was looking for and like you said, no one is writing about them. I was planning on using the legacy plugin until I read this. Thanks for this!

You’re welcome cowboycoded. Also thank you for referencing me in your blog post.

Thanks for the help, this saved me some time and wasn’t 100% clear in the rdoc

[...] Rails 3 is no longer Prototype-oriented, Rails 3 code is now JavaScript framework agnostic and there are many incompatible changes that require your attention. Learn more about Unobtrusive JavaScript in Rails 3. [...]

Francis says:

If using prototype, an easy way to handle callbacks on all Ajax requests is to use the Ajax.Responders. Something like this, which would show/hide a div with a loading icon (or whatever it has in it), with each ajax request. Include in the application layout:

  Ajax.Responders.register( {
    onCreate: function() { $('loading').show(); },
    onComplete: function() { $('loading').hide(); }
    });
WLiCPSC says:

Hi there: just seen this comment, I desperately need this loading image or screen to show up, can you tell me which exact file to put this piece in? Thanks very much.

Note, importantly, that the correct signature for the callback is as follows:

.bind('ajax:success', function(evt, data, status, xhr) {

The example as written would work, but is somewhat misleading.

Nucc says:

Can I ask something. I have a problem with remote form in Rails 3. I’ve created button elements with divs and I have an <a> tag to submit my form. My question is how I should construct this <a> element?

If I use data-remote and data-method in the <a> tag, it behaves like a seperated form and it sends no input value from my form (in the rails.js it constructs an own form)

If I use only data-remote, it doesn’t send any POST parameters to the server, only the header information.

If I use only the data-method, or writing it’s onclick slot to call form’s submit() method, it behaves a plain form without any AJAX and redirects to the page contained by the href attribute.

Have you got any idea, how can I solve this (seems to be really simple) problem?

Nucc says:

Hey guy, you should escape your inputs … there’s an < a > before the “tag to submit my form”

nathanvda says:

Great article. I especially appreciated the part about the remote callbacks, i was unable to find that anywhere else. Thank you very much!

erwin says:

Thanks for all these info… I am trying to rewrite some Rails 2 app w Rails 3…
could not find any example of replacing the onclick on an input checkbox w an Ajax request in Rails 3

I wrote

= check_box_tag “selection”, “1″, false, {:id => user.id, :remote => true, :url => showHideMenuItem_admin_user_path }
but it’s not generating any Ajax request at all… any clue ?

erwin

erwin says:

I should be using the prototype_helper onclick => remote_function(), but is it going to be replaced too ?

AFAIK, the check_box_tag helper doesn’t support the :remote option.
You need to create an AJAX call based on the onclick event.

In jQuery you can use the .click() handler.

Chris Ledden says:

Thanks for the post. I am new to incorporating Javascript into Rails, and this certainly helps a lot.

I’m struggling with the best method to dynamically insert items into a “select” list box. I am trying to achieve the paradigm where you display a list of items in the list, with a “…add new item” option, and if the user selects this, it pops up a new window with the appropriate New controller, allows them to add a new value, and close the pop up, and it automatically selects the new item in the list.

Any suggestions on the best way to implement this?

Keep up the great work.

Chris, the pattern is quite simple.

1. Create the select.
2. Populate the select with existing items plus a default item with default value (e.g. 0) and text “Add a new item”
3. Attach a new #blur event that checks whether the value is the default value
4. If so, open a popup (modal?) to add the new item.

Mac says:

What’s the recommended replacement for other prototype helpers like page.replace_html ?

If you are using jQuery, you use the html() method.

$("#element").html("< %= variable %>");
Wagner Pereira says:

Carletti,

Wouldn’t be better inject the code using content_for on the end body section, before close it? Instead of the injection in the head of the page as you mentioned.

I would like to confirm that.

Thanks in advance.

[...] Unobtrusive JavaScript in Rails 3 – by Simon Carletti [...]

[...] I want to drop use of the Jrails plugin and harness unobtrusive JavaScript [...]

bmihelac says:

Notice problem with handling remote form example:

$(“#tool-form”).bind(“ajax:success”, function(data, status, xhr) {
$(“#response”).html(status);
});

this anonymous function will receive 4 arguments indeed, first being ‘event’, so proper code should be:

$(“#tool-form”).bind(“ajax:success”, function(event, data, status, xhr) {
$(“#response”).html(data);
});

Are you sure of this?
See https://github.com/rails/jquery-ujs/blob/4ece456c505b6929cde996100770a67b1a805cfc/src/rails.js#L59-61

bmihelac says:

Yes, I am. When event is triggered from rails.js, JQuery would take that event and dispatch it to registered listeners, in this case our anonymous function with event as first param.

This is from JQuery .bind() documentation:
>> The handler callback function can also take parameters. When the function is called, the JavaScript event object will be passed to the first parameter.

Also, it makes more sense returned data to be in named data rather then status :)

regards,
Bojan

ming yeow says:

Hi there! There seems to be a bit of confusion:

.bind(‘ajax:before’, function(){ … } ) => this is for BEFORE execution
.bind(‘ajax:loading’, function(){ … } ) => this is for WAITING for execution

Also, how do we refer to the actual event at any given point in time of the execution?

Corey says:

It’s already in the comments, but it appears it hasn’t yet been taken into account by Simone yet so here it is again in hopes that it’ll be resolved:

The correct callback arguments should read `event, data, status, xhr`, then you can call `$(‘#response’).html(data);` as expected.

I was having trouble with this until I checked the jQuery API docs that clearly state that callbacks triggered with `.trigger()` get the event passed as the first parameter, regardless of whether or not you specify additional parameters via the second argument (to the trigger method, that is).

Thanks Corey. I finally had the time to update the article with all the comments posted so far. :)

Very nice article! Thanks

Mark Clark says:

Thanks for your tutorial. I have a question about repeatedly updating a that is not in a form by using jquery and unobtrusive javascript. I want to update a progress bar to inform the user the status of a long process (the process is not files uploading). I loop through several tasks in a controller and would like to update the progress bar after each task is executed in the loop. What code should I add to the controller to refresh the call the javascript and refresh the view ?

murato says:

Hi, great article.
I have a one question. Why ‘ajax:success’ callback can be invoked two times?

[...] parsley stands to kitchen. You find it almost everywhere. Think about jQuery Mobile, Sencha Touch, unobtrusive Rails 3 helpers, Cappucino, HTML 5 Modernizr library, etc. these are just a few examples of how JavaScript is [...]

Dominic says:

According to this pull request, ajax:loading has been replaced with ajax:beforeSend, and a few other callbacks have been trimmed:
https://github.com/rails/jquery-ujs/pull/56

James says:

hello,
Which js file do you put the javascript code definitions in for the section “Then, bind the function to toggle the spinner visibility to the appropriate AJAX events. Also, on success replace the content of #response with the response data.”"?
application.js?

Can be any .js file included in your application. In Rails < 3.1 it can be application.js, in Rails >= 3.1 you might want to use a different .js file because the application.js is a manifest file.

Mrgreenfur says:

Nice article! I was toying with the ajax:success handlers and I think you got your order of arguments wrong. It should be:

bind(‘ajax:success’,function(status, data, xhr){ …})

I’m sure the order is correct. Make sure you are adding the event parameter as well.

(event, xhr, status, error)
Mike Bailey says:

This post has withstood the test of time. That’s for laying things out so clearly Simone!

Joe McGouran says:

Simone – very interesting article.

I have acollege project to integrate into / enhance a Rails 3 scaffold app with Ajax, JQuery, dynamic DOM update,CSS, etc.. Do you know of any other papers that describe how to go about this.

Look forward to your response.

I’m sorry, but I don’t have any link handy. However, there are plenty of tutorials available online.
Just make sure to discard outdated posts.

Keith says:

Thanks for helping me better understand unobtrusive javascript in rails 3.

There’s a grammatical mistake I found in the “So What?” section. You have “what does this means”, but it should be “what does this mean”. Any time you have something like “do”, “does”, or “will”, etc. in front of the verb, you would use “mean” instead of “means”. “This means…” vs. “What does this mean?” or “This does mean…”. Hope that helps.

Gordon says:

hi there,
thank you for this tutorial.
I’m reimplementing an existing rails 2.3.8 app with rails 3.1.x

As I follow this tutorial, it seems that my _path helper url value doesn’t get interpolated in the javascript.

For example, in your tutorial,
1
2
3
4
5
6
7
8
9
10
// Append the function to the “document ready” chain
jQuery(function($) {
// when the #search field changes
$(“#search”).change(function() {
// make a POST call and replace the content
$.post(, function(data) {
$(“#results”).html(data);
});
});
})

the live_search_path does not get translated into an actual path.

Please help.

Tiago Sarri says:

Thanks for helping me, the ajax:failure event note if user cancel the xhr

I think that ‘ajax:failure’ has been replaced with ‘ajax:error’. See source here: https://github.com/rails/jquery-ujs/blob/82292010fb1743f038ab72b1f1e994e91be3eda3/src/rails.js#L148

Dan Garland says:

“Placing a javascript_tag in the middle of a page is probably not so unobtrusive”

It defeats the purpose as far as I can tell.

Marlin Pierce says:

Let me be clear up front that this was a great article; it was very helpful; it was in fact the definitive statement which convinced us that we needed to exclude prototype and Rails prototype helpers in our non-legacy development.

However, I did not find the justification for Rails switching from prototype to jQuery convincing. The observer example was not less verbose. I don’t see an advantage of Rails being no longer prototype oriented. I don’t consider using jQuery to be framework agnostic, as it depends on the jQuery framework.

Maybe I am missing that, unlike the prototype support, Rails is decoupled from jQuery, as it does not have jQuery dependent helpers. Maybe that’s it. I was not happy when I first learned Rails that it was prototype dependent. However, once using it, taking it away is a decision I disagree with.

I also disagree that it’s a positive that the jQuery way, forces developers to have a deeper JavaScript knowledge than in the past. There are a number of systems to gloss over JavaScript, gwt, extJS, and jQuery. JavaScript is a little clunky, and the DOM api is definitely clunky.

My hope would be that a JS gloss framework became so popular that it was incorporated natively in browsers. For instance, observers could be added to the JavaScript foundation. Rails selection of prototype, brings prototype almost to a justifiable standard as a candidate for such inclusion. Abandoning prototype, and switching frameworks undermines this hope.

random8r says:

What is really needed is a ‘full stack’ comms JS framework on top of a shim layer between jQuery or Prototype (or any other framework) that allows us to build things on top of existing JS frameworks… so it’s EASIER than it has been with the prototype library, not harder, as it is now. We effectly have to roll our own functionality for what WAS provided as built in previously. Granted what was previously built in was kludgy and really crap, but this the upgrade path of Rails is generally “sucked in, everything’s changed”. It’s a bit… fail.

Lucas says:

Great article! Helped me a lot. What I ran into though is the fact that the “ajax:failure” event is no longer called that, but “ajax:error” instead. Maybe worth an update? :)

finnnnnn says:

Great Article thanks.

One comment, as of jquery 1.7 .on() is preferred to .bind(), may be worth updating your article to reflect that. http://api.jquery.com/bind/

Mitko says:

Great article! Many thanks!

Faiz says:

Great. Very help full for upgrading to rails 3. Thanks.

Thank you! Finally i have a clean way to use ajax!

Add a Comment




Follow Me
    Random Quote