21
Feb 09

Proper MooTools Ajax Requests

If you read this you are probably aware that I use Ajax (allows a page to load new content without reloading the page) alot. I really like it. It allows me to control my users experience, and doesn’t require flash. It, if done properly, also degrades nicely. Meaning, if the browser does not support it, the user can still proceed to seeing the content. Just not exactly the same way. (often just navigates to the content, and leaves the current page behind).

Because I love it so much, and I see most people using it incorrectly, I want to go over the correct way.

First of all, everything you are doing in MooTools should be between this. The reasoning is that, this waits for the DOM (Document object model… basically the HTML structure) to be completely loaded and ready.

Anything that fires before this would risk not working properly.

window.addEvent('domready', function(){

});

Now we are going to make an instance of the Request class (ajax)

window.addEvent('domready', function(){
	var ajax = new Request();
});

This is actually most often where people go wrong. A lot of people think that this should go inside of a click event listener or something like that… EG

THIS IS WRONG!!!!!!!!!

window.addEvent('domready', function(){

	$( 'elementID' ).addEvent('click', function(e) {
		var ajax = new Request();

	});		

});

The reason it is wrong is because this creates a new Request instance every time elementID is clicked. Basically that is like buying a new car every time you want to go to the grocery store. Not only that, but you dont even get rid of the previous cars. What you want to do is get one car, and drive it where ever you want to go.

So in full what you want to do is something like this

window.addEvent('domready', function(){

	var ajax = new Request({
		url: 'fileToRequest.php';
		onRequest: function(txt){
			$('toLoad').set('html', 'Loading...');
		},	

		onSuccess: function(txt){
			$('toLoad').set('html', txt);
		}

	});	

	$( 'elementID' ).addEvent('click', function(e) {
		ajax.send();
	});		

});	

And… If you want to drive the care somewhere else, you can so this.

		ajax.setOptions({"url": 'NewPlace.php'});
		ajax.send();

 

So make one car, dive it where ever you need.

Note, there are times when you need multi cars, like if you need to pick up info from multi places at the same time, or you need different types of cars.


Comments are closed.


Copyright © 2012 ASM | a blog
Proudly powered by WordPress, Free WordPress Themes, and Search Marketing