Unobtrusive deleting with Rails and jQuery

Posted by andy gaskell on Nov 15th, 2009

I’m going to cover creating a sample Rails application, taking a look at how destroy works by default and how we can improve accessibility by writing unobtrusive JavaScript using the jQuery library.

First let’s create a new Rails application. We’ll call it ajaxstore.

Now let’s create some scaffolding and take a look at how it works.

Launch your favorite toob surfer to http://localhost:3000/products and create a few products to use. Back at the products list let’s take a look at the Destroy links. From a user’s perspective if you have JavaScript enabled you’ll get a confirmation dialog. If the user has JavaScript disabled he will be brought to the show action, and probably feel a little lost. From a developer standpoint there’s a lot of unnecessary repeated JavaScript on the Destroy links. Let’s get this fixed.

Let’s remove the default JavaScript that Rails adds to our project since we’re going to use jQuery.

Now let’s download jQuery.

Open up routes.rb – we need to add an option to the products resource route. I’m using delete as my option. You could overload destroy but in my opinion that makes the destroy action less cohesive.

We now need to add a view for our new action. Create a new file named ‘delete.html.erb’ in your product views directory. We’ll keep it fairly simple, and ask the user to confirm the destroy.

At this point we need to do some refactoring. Open up the Products controller and look at all the places we’re calling Product.find(params[:id]). We’re going to refactor that into a before filter and simplify the controller a bit. Here’s the entire controller.

Here we removed the edit and show actions, removed the first line from the update and destroy actions, created a method to load the product, and finally setup the filter. Now lets change how we generate our destroy links in the index and show views. First open up the Product index view and change the destroy link (should be around line 15) to this.

We’ll use the delete class in our JavaScript to handle delete clicks. For the show view, just remove the destroy link altogether. Browse to http://localhost:3000/products and create a product if need be, and now if you click on the “Delete” link we are brought to our delete view and our non-JavaScripting friends want to give us high fives. For the rest of our users, navigating to a new page is a bit much for deleting a product. Open up the layout file and add this under the stylesheet_link_tag.

We’re creating a AUTH_TOKEN variable so that when we make a POST, PUT or DELETE via ajax we can pass along the authentication token. Let’s add some jQuery code to application.js to handle deletions. This JavaScript has been pulled from a larger application so some parts of are maybe a little too industrial strength for a blog post, but I’m going to focus on the Rails side and less on the jQuery. If there’s enough demand to go into details on the jQuery we’ll talk more about it – the main points are the ajaxSend handler and the a.delete click handler.

We also need to make some changes to our CSS file – here are the styles we need to add.

Let’s get Rails setup to do some ajax’n. There are a couple changes you need to make to every application. Add these lines under the protect_from_forgery line in your application controller.

And under those lines add the corresponding methods:

The set_xhr_flash method removes the flash if the current request is an ajax request. If we don’t clear the flash on an ajax request the next time the user makes a full http request the user will see the flash message. The other method is for safari and IE browsers – we’re correcting some headers for ajax requests. One last change to our destroy action in our Products controller and we’re good to go.

Start up your browser and server if need be. We are now fully web 2.0. JavaScripters and NonJavaScripters can use our app equally and that makes us totally rad web folks. You can download the full project over at github.

Bulletproof Ajax with ASP.NET MVC (this time with jQuery)

Posted by andy gaskell on Aug 10th, 2008

As a follow up a recent post about using unobtrusive javascript and Ajax in your ASP.NET MVC applications, I ported the Bulletproof Ajax bookstore application to use jQuery instead of Hijax. This led to more terse code – lines of javascript were reduced from 178 to 41. If you’ve spent at least few hours jQuery then you should find that the new code is also more readable. No server side code changes were necessary.

jQuery is also really easy to extend – I wrote a couple of extensions that would be usable throughout an application. Here’s the extension I wrote to produce the ubiquitous yellow fade effect:

(function($) {
   $.fn.yellowFade = function() {
    return this.css({backgroundColor: "#ffffcc"})
    .animate({backgroundColor: "#ffffff"}, 1500, "linear");
   }
 })(jQuery);

Calling this method flows with the rest of jQuery style chaining of methods:

function(data) { $("div#basket").html(data).yellowFade(); });

This one liner is a callback from our http post to the /Cart/AddProduct. The data parameter contains the response from the server. $("div#basket") is getting the container div from our shopping cart. Then we replace the html within the shopping cart div with the response from the server and follow it up with a yellow fade to provide user feedback.

Code is downloadable here. The demo.

Microsoft’s Ajax Support for ASP.NET MVC Fails (for now)

Posted by andy gaskell on Aug 4th, 2008

But it’s not an epic fail (for now). It’s important that my sites function without javascript or Ajax support. Ajax should be used enhance usability and is not a requirement to access my content.

I was checking out Hanselman’s Ajax example (the truly lazy can download the code here) and I was pretty bummed when I disabled javascript and saw this:

failure on the ajax front

Oops. That’s probably not what the user expected. Maybe there’s some way to get the AjaxHelper to save us but none of the 10 overloads for the ActionLink or Form methods stood out to me. Until I get around to really learning jQuery, I’ll stick with writing Ajax by hand. This allows me to request different urls based on whether or not javascript is enabled. And writing your own javascript really isn’t that hard – go grab a good book.

Next »