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

<(anchor) href="ajax.php" class="ajax">Sent Via AJAX </a>
<(anchor) href="ajax_alternative.php" class="ajax">Also Sent Via AJAX </a>
 
<(div) id="message">I am filled with the results of our AJAX requests. </div>

It’s 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?

Posts Tagged with…

Write a Comment

Your email address will not be published. Required fields are marked *