smallroomsoftware.com

Graceful degredation of ajax partial page loading without much hassle

Posted on July 19, 2006

Okay, this is pretty obvious when you think about it but I think it's the kind of thing you have to read somewhere to actually hammer it home. There's a very straightforward principle you can use to make your fancy AJAX powered partial page reloads degrade nicely when javascript isn't available (or just fails).

Say you have an "add to cart" link and you want it to use an AJAX request to inform the server that the item is to be added to the cart and to also get some html to update a "mini-cart" div. Well, what you should do is code this without any AJAX/javascript first. Have the link just target an action, e.g. "/cart/add_product?id=123". The action should then redirect to the cart details page or wherever. Fine, that works nicely for non-javascript browsers.

Now, write your link onClick handler so it pulls the same URL from the link (using the DOM) and makes an XMLHttpRequest. This time though, the server should return just the html fragment to be updated. How does the server know to return a fragment? Most AJAX libraries add a special header to the request identifying it as an AJAX request.

Something like Ruby on Rails should of course be able to do all of this for you! But, by default, the link_to_remote function inserts "#" into the link's href parameter and you have to repeat the URL parameters to get the desired result.

Post a comment
Comment



If you can read this, you don't use a typical webbrowser that plays nice with CSS.
Please do not fill in anything here!



Hosting by site5.com