Making Every Specified Link Send Via Ajax Using MooTools

This is a relatively simple concept and is nothing to elaborate but I wanted to share a small piece of code that will take every link with the class of “ajax” and access it using AJAX instead of actually going to that page. This using the same Request instance which will keep it optimized and manageable. MooTools is going to make this nice and easy on us…

Usage

JavaScript

var ajax_request = new Request(
{
	onSuccess: function(responseText, responseXML)
	{
		$('message').set('html', responseText);
	}
});

$$('.ajax').each(function(item){
	var url = item.get('href');
	item.addEvent('click', function(event){
		ajax_request.options.url = url;
		ajax_request.send();
		return false;
	});
});

HTML

Sent Via AJAX
Also Sent Via AJAX

I am filled with the results of our AJAX requests.

Its incredibly simple so no demo for this. The important concept here is that we are using the same request and pulling the href attribute base on a class selection. So changing something from AJAX to regular is as easy as adding or removing the class “ajax”. Pretty cool eh?

Popular Posts

Help The Javascript Blog

If you would like to write for The Javascript Blog or submit a plugin or class please feel free to contact us.


5 Responses

12.11.10

Very cool, thankyou for sharing.

PS Love this blog, just found it and it is full of great stuff

Wow thanks Paul. :-)

03.05.11

Hello..

quick question.. what is the benefit of accessing a link using AJAX rather than actually going to that page ?

I’m a little confused on this one.

thanks

While it depends a lot on the use case, often times it is beneficial from a user experience side to pull information using AJAX rather than a full page refresh. By no means does this post recommend only using AJAX ever but using ones intellect to decide when a good time and place for it is. For example, pulling in footnotes, or more detailed contact information.

03.23.11

I still have not had a chance to really use this after an initial play/test, because I have started using jQuery which is a bit more accessible for me. MooTools seems a bit more of a pro coders tool.

@sol, the use of ajax in small measures can change the whole feel and quality of a site. You would probably not use it to import a whole new pages worth of content, but as Merrick said, for small bits of extra info or extra content from any database, it is invalueable. As an example, retrieving a users profile, so without leaving a comments page, you could see the profiles of the members that have commented.

Paul D.

Leave Your Response

* Name, Email, Comment are Required