gaskell.org » ajax http://gaskell.org picking up where teh rest leave off Tue, 07 Jun 2011 16:38:59 +0000 en hourly 1 http://wordpress.org/?v=3.3.2 Unobtrusive deleting with Rails and jQuery http://gaskell.org/unobtrusive-deleting-with-rails-and-jquery/ http://gaskell.org/unobtrusive-deleting-with-rails-and-jquery/#comments Sun, 15 Nov 2009 07:33:18 +0000 andy gaskell http://gaskell.org/?p=194 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.

]]>
http://gaskell.org/unobtrusive-deleting-with-rails-and-jquery/feed/ 1
Bulletproof Ajax with ASP.NET MVC (this time with jQuery) http://gaskell.org/bulletproof-ajax-with-aspnet-mvc-this-time-with-jquery/ http://gaskell.org/bulletproof-ajax-with-aspnet-mvc-this-time-with-jquery/#comments Sun, 10 Aug 2008 22:11:11 +0000 andy gaskell http://gaskell.org/?p=81 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.

]]>
http://gaskell.org/bulletproof-ajax-with-aspnet-mvc-this-time-with-jquery/feed/ 1
Microsoft’s Ajax Support for ASP.NET MVC Fails (for now) http://gaskell.org/microsofts-ajax-support-for-aspnet-mvc-fails-for-now/ http://gaskell.org/microsofts-ajax-support-for-aspnet-mvc-fails-for-now/#comments Tue, 05 Aug 2008 04:10:22 +0000 andy gaskell http://gaskell.org/?p=73 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.

]]>
http://gaskell.org/microsofts-ajax-support-for-aspnet-mvc-fails-for-now/feed/ 1
Bulletproof Ajax with ASP.NET MVC http://gaskell.org/bulletproof-ajax-with-aspnet-mvc/ http://gaskell.org/bulletproof-ajax-with-aspnet-mvc/#comments Sun, 03 Aug 2008 03:26:26 +0000 andy gaskell http://gaskell.org/?p=59 After reading the excellent Bulletproof Ajax by Jeremy Keith, I thought porting the Bulletproof Books sample application to ASP.NET MVC would be a great first attempt at building an ASP.NET MVC application. One of the main points of Bulletproof Ajax is that Ajax should be used to enhance usability and not to make Ajax a requirement to access your content. My version of the Bulletproof Books Shop also makes Javascript and XMLHttpRequest support optional.

Keeping the site accessible to most web browsers took some extra work and consideration when building the Controllers. I decided that any HomeController actions would render html for the entire page.

   13         public ActionResult Index()

   14         {

   15             ViewData.Model = Product.Products;

   16             return View(“Index”);

   17         }

   18 

   19         public ActionResult AddProductToCart(string productID, int quantity)

   20         {

   21             CartController cartController = new CartController();

   22             cartController.AddProduct(productID, quantity);

   23             return Index();

   24         }

   25 

   26         public ActionResult RateProduct(string productID, string rating)

   27         {

   28             RatingController ratingController = new RatingController();

   29             ratingController.RateProduct(productID, rating);

   30             return Index();

   31         }

Controllers that refresh partial chunks of html will know how to respond to actions (add product to cart, rate a product) and render views mapped to MVC user controls. The client will make http requests to different urls based on javascript support in the browser. For example to add a product to a cart with javascript enabled, the javascript will make a post to /Cart.mvc/AddProduct and the server will response with a chunk of html. To add a product with javascript disabled the client will post to /Home.mvc/AddProductToCart and the server will respond with an entire page. The HomeController ends up forwarding the call to the appropriate controller so we’re able to avoid duplicating logic.

   28         public ActionResult DisplayCart()

   29         {

   30             Cart cart = GetCart();

   31             return View(“Cart”, cart);

   32         }

   33 

   34         public ActionResult AddProduct(string productID, int quantity)

   35         {

   36             Cart cart = GetCart();

   37             Product product = Product.Products.Find(s => s.ID == productID);

   38             cart.AddProduct(product, quantity);

   39             SetCart(cart);

   40             return View(“Cart”, cart);

   41         }

One thing I’m not sure about is state management in ASP.NET MVC, so I’m currently storing the cart and ratings in session.

   22         private Rating GetRatings()

   23         {

   24             Rating rating = System.Web.HttpContext.Current.Session["Rating"] as Rating;

   25             if (rating == null)

   26             {

   27                 rating = new Rating();

   28             }

   29             return rating;

   30         }

   31 

   32         private void SetRating(Rating rating)

   33         {

   34             System.Web.HttpContext.Current.Session["Rating"] = rating;

   35         }

You can download the source here.
]]>
http://gaskell.org/bulletproof-ajax-with-aspnet-mvc/feed/ 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 Buy Generic Methotrexate No Prescription Viagra Walmart Best Online Pharmacy For Cialis Generic Buying Femara Canadian Pharmacy No Prescription Needed Alesse Purchase No Prescription Mircette Cheapest Levitra From India Buy Tablets Actonel Online No Prescription Antibiotics Online Ordina Viagra Tricor No Prescription Acheter Diabecon Viagra Ou Equivalentes Amoxil Buy Online Cheap Cafergot Order Buy Best Generic Baclofen Tablets Without a Prescription Seroquel Order Online No Perscription Purchase Lexapro Online Without Prescription Buy Viagra Online Tabs Cheap Generic Substitute Viagra Purchase Lexapro Purchase Viagra In Australia Buy Viagra In Canada Fast Canadian Pharmacy Toronto Zithromax Order Bupropion Next Day Delivery Canadianlab Viagra Tablets Buy VentolinZovirax And Cost Levitra 20mg Tablets Generic Viagra Free Pills Viagra Professional Buy