Giving the Anchor tag some Ajax Lov'n
Posted Tuesday, May 13, 2008It seems I’m forever needing to submit links using an XMLHttpRequest rather than the default full-page refresh. One approach commonly used in the Rails community is to render each link with the JavaScript already in place. My preferred approach however is to keep the HTML as free from JavaScript as possible and unobtrusively add behaviour using LowPro.
LowPro already comes with a built-in behaviour for links but sometimes I need something little more complex than simply submitting the request and so I usually end up doing the following:
anchor = ...;new Ajax.Request(anchor.href, { method: "get", parameters: ... });
Granted that’s not a lot of effort but it still felt as though I were repeating myself and that the overall intention of my code was largely obscured by the infrastructure. It then struck me that submitting a form using the Prototype JavaScript framework is almost trivial:
form = ...;form.request({ parameters: ... });
So I cooked up a version for anchors as well:
Element.addMethods("A", {request: function(anchor, options) {new Ajax.Request(anchor.href, Object.extend({ method : "get" }, options || {}));}});
Now I can submit links in pretty much the same was as I do forms:
anchor = ...;anchor.request({ parameters: ... });
I’m wondering what other possibilities might occur were I to add a serialize() method to extract the request parameters.
About Simon
Husband, Father, One-time Entrepreneur.
Aka Haruki Zaemon. Aka Sampy.
In my younger years I wanted to save the world; now I'm happy solving bigger problems than I create.
If I didn't need to work I'd be teaching Aikido and spending all my free time with my amazing wife and two children in Woodend, Victoria, Australia.
Books
Beginning Algorithms
with James Ross

COMMENTS
blog comments powered by Disqus