Basic Ajax Requests Using MooTools 1.2

Written by David Walsh on Wednesday, April 9, 2008


This article may feature code that is no longer best practice in MooTools.
Click here to learn what has changed to make your code framework-compatible.

Ajax has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made Ajax so simple that a rookie developer can get their dynamic pages working in no time.

Step 1: The XHTML

<p>
	<a href="http://davidwalsh.name/dw-content/moo-basic-ajax-example.php" id="ajax-alert">Click here</a> to receive a special message from a PHP script via a javascript alert.
</p>
<p>
	<a href="http://davidwalsh.name/dw-content/moo-basic-ajax-example.php" id="ajax-replace">Click here</a> to populate the element below with the special message.
</p>
<div id="message-here">
	Special message will appear here.
</div>

Here we define two links and a message box. Both links will trigger Ajax calls but there’s a difference in how the result is handled. The first will take the response and output the response in a javascript alert box. The second link makes an Ajax call but returns the result into the message box.

Step 2: The PHP

echo 'Hello from PHP!!';

There’s very little PHP involved. In this case, we do no “real” programming — just a simple echo statement.

Ste 3: The MooTools Javascript

//on dom ready...
window.addEvent('domready', function() {

	/* ajax alert */
	$('ajax-alert').addEvent('click', function(event) {
		//prevent the page from changing
		event.stop();
		//make the ajax call
		var req = new Request({
			method: 'get',
			url: $('ajax-alert').get('href'),
			data: { 'do' : '1' },
			onRequest: function() { alert('Request made. Please wait...'); },
			onComplete: function(response) { alert('Response: ' + response); }
		}).send();
	});

	/* ajax replace element text */
	$('ajax-replace').addEvent('click', function(event) {
		//prevent the page from changing
		event.stop();
		//make the ajax call, replace text
		var req = new Request.HTML({
			method: 'get',
			url: $('ajax-replace').get('href'),
			data: { 'do' : '1' },
			onRequest: function() { alert('Request made. Please wait...'); },
			update: $('message-here'),
			onComplete: function(response) { alert('Request completed successfully.'); $('message-here').setStyle('background','#fffea1');
			}
		}).send();
	});
});

To create an Ajax request, you must create an instance of the Request class. We provide our request with the method (either get or post), the URL to ping, optional data information, and optional onRequest and onComplete event handlers.

In the first block, we accept the response in the onComplete event handler and alert it out to the screen. The second MooTools block uses the Request.HTML class instead of the Request class. Use the Request.HTML class when you intend to replace a specified element’s innerHTML with the Ajax request’s response.


Follow via RSS Epic Discussion

Commenter Avatar April 09 / #

Note that the YUI team recommends using “GET” for AJAX when possible. Good primer on MooTools AJAX, David!

David Walsh April 09 / #
david says:

I like using $_GET too, unless there’s a ton of data being passed, in which case why use Ajax?

Commenter Avatar April 10 / #
Tom says:

I’m not a coder, for me this tutorial is a really nice starting point :)

Anyway I don’t like Ajax so much, it is often a bad solution because of accessibility issues.

Commenter Avatar June 23 / #
Crispijn says:

I’m upgrading my site to mootools 1.2 and I can not find where the parameter ‘data’ is used for. Can you tell me where it is for?

David Walsh June 23 / #
david says:

@Crispjin: Good question. I use “data” because some hosting providers don’t allow empty ajax requests. Dreamhost is one of those providers. For that reason I always use “data”, even though there is a populated querystring.

Commenter Avatar July 26 / #
Joe says:

I am having a problem with the Request. In my site I am using URI Segments. When I am on the page I want to make the request from I use Segment 3 as specific page, example “index.php/sites/view/1″.
“sites” is my controller ,”view” is my function within that controller and “1″ is just a variable. When Request.HTML is launched it always put the full URL of the page I am on http://localhost/index.php/sites/view/1 + whatever page URL I put in the request. Subsequently my call will return the page I am on within the element that is updated. Is there a way to change the URL it is requesting? I have tried to replace the whole URL with no change. It just adds the whole URL to the URL. Also the request will vary if the URI has a trailing”/”. If the slash is there the request adds the last segment, no slash it removes the segment becasue it thinks the last segement is file. Any suggestions would be greatly appreciated. By the way, great tutorial, Thanks.

Commenter Avatar July 27 / #
Henry says:

This just made my day. Thanks for this tutorial!

Commenter Avatar September 28 / #

Whats the name PHP file. How call from XTML with parameter?

Commenter Avatar October 08 / #
Morten Slott Hansen says:

Hi,
I want to do multiple ajax requests all running async – but that seems to break things. I basically have a function taking a placeholder parameter and a url which returns the content.

updateContent(‘content1′, ‘ajax/content1′);

And the function is defined as:

function updateContent(placeholder, page) {
var req = new Request.HTML({
method: ‘post’,
async: true,
url:’http://dev.247ms.com/servlets/2452306090224Dispatch/31/jspforward’,
// Url parameters
data: {
file: ‘./home/msh/html/shopTemplateAjax/index.jsp’,
page: page
},
// Show ajax loder gif prior to request
onRequest: function(item) {
$(placeholder).innerHTML = “<center><img src=’http://dev.247ms.com/~msh/shopTemplateAjax/public/pix/ajax-loader.gif’/></center>”;
},
// Show requested HTML and eval script tags
onSuccess: function(html) {
$(placeholder).set(‘text’, ”);
$(placeholder).adopt(html);
},
// Alert response text.
onFailure: function(item) {
alert(item.responseText);
}
}).send();
}

However when I call the updateContent multiple times in a row I get really weird results which would indicate that they kinda step on each other toes or something. Changing the async to false fixes this – but that really defies the whole purpose of what I’m trying to do.

Any suggestions ?

Commenter Avatar October 14 / #
Markus says:

thank you for this great example. it works but the request is always ‘undefined’ and i don’t know why. Have you any idea about the reason? thank you.

Commenter Avatar October 14 / #
Morten Slott Hansen says:

Try this instead – with onTimeout also which is awesome:

http://code.google.com/p/mootimeout/

Request = new Class({
Extends: Request,

options: {
/*onTimeout:$empty,*/
timeout:false
},

send: function(options){
var timeout=(this.options.timeout || (options ? options.timeout: null));
if (timeout) {
this.timeoutTimer=window.setTimeout(this.callTimeout.bindWithEvent(this), timeout);
this.addEvent(‘onComplete’, this.removeTimer);
}
return this.parent(options);
},

callTimeout: function () {
if (!this.running) return this;
this.running = false;
this.xhr.abort();
this.xhr.onreadystatechange = $empty;
this.xhr = new Browser.Request();
this.onFailure();
this.fireEvent(‘onTimeout’);
},

removeTimer: function() {
window.clearTimeout(this.timeoutTimer);
}
});

function updateContent(placeholder, page, ident, returnPage) {
var req = new Request({
method: ‘get’,
async: true,
url:’http://dev.247ms.com/servlets/2452306090224Dispatch/31/jspforward’,
evalScripts: true,
timeout: 2000,
headers: {‘Pragma’: ‘no-cache’},
// Url parameters
data: {
file: ‘./home/msh/html/shopTemplateAjax/index.jsp’,
page: page,
flush: ‘true’,
ident: ident,
returnPage: returnPage,
returnPlaceholder: placeholder
},
// Show ajax loder gif prior to request
onRequest: function(item) {
$(placeholder).innerHTML = “<center><img src=’http://dev.247ms.com/~msh/shopTemplateAjax/public/pix/ajax-loader.gif’/></center>”;
},
// Show requested HTML and eval script tags
onSuccess: function(html) {
$(placeholder).set(‘html’, html);
},
// Alert response text.
onFailure: function(item) {
// alert(item.responseText);
},
onTimeout: function(item) {
updateContent(placeholder, “ajax/timeout”, ident, page);
}
}).send();
}

I also found the cause of my problems – it was a race condition within my java servlet where my response object got nullified by the next ajax request – so case closed for me :)

Commenter Avatar November 13 / #
sam says:

Thanks very much!

Commenter Avatar December 16 / #

Howdi David,

I love your posts and tutorials. They’re all organized so well and your site is clean and easy to navigate :)

I had a question. Is there an easy way to make the url: $(‘ajax-alert’).get(‘href’), part of this script triggered by a js variable rather than a fixed ID or that would break it? That way one could do multiple ajax requests from different links on a page.

Commenter Avatar February 02 / #
rain says:

thank u thank u thank u!!!!

Commenter Avatar February 07 / #
confiq says:

Hi David,
Very nice and easy tutorial, however it would be nice to see how to get <form data from HTML and pass it to request…
regards

Commenter Avatar February 13 / #
johan says:

Thanks,
Great as always. I keep coming to your articles again and again!!! :)
/Johan

Commenter Avatar February 16 / #
BeN says:

Hi David, i am a big fan of your blog, saludos desde Mexico

Commenter Avatar March 18 / #
Sonal says:

Hi All,

below is the code i am trying to recreate using the tutorial but i get the following error in FF, can somebody help me and tell me what is happening. I get Access denied in IE7. I have downloaded the latest mootools-1.2.1.-core-yc.js file from the mootools website.

[Exception... "'Permission denied to call method XMLHttpRequest.open' when calling method: [nsIDOMEventListener::handleEvent]” nsresult: “0×8057001e (NS_ERROR_XPC_JS_THREW_STRING)” location: “” data: no]

Untitled Page

#log {
background: #f8f8f8;
border: 1px solid #d6d6d6;
border-left-color: #e4e4e4;
border-top-color: #e4e4e4;
padding: 0.3em;
margin-top: 10px;
}

#start a {
font-weight: bold;
}

//on dom ready…
window.addEvent(‘domready’, function() {

/* ajax alert */
$(‘ajax-alert’).addEvent(‘click’, function(event) {
//prevent the page from changing
event.stop();
//make the ajax call
var req = new Request({
method: ‘get’,
url: $(‘ajax-alert’).get(‘href’),
data: { ‘do’ : ‘1′ },
onRequest: function() { alert(‘Request made. Please wait…’); },
onComplete: function(response) { alert(‘Response: ‘ + response); }
}).send();
});

/* ajax replace element text */
$(‘ajax-replace’).addEvent(‘click’, function(event) {
//prevent the page from changing
event.stop();
//make the ajax call, replace text
var req = new Request.HTML({
method: ‘get’,
url: $(‘ajax-replace’).get(‘href’),
data: { ‘do’ : ‘1′ },
onRequest: function() { alert(‘Request made. Please wait…’); },
update: $(‘message-here’),
onComplete: function(response) { alert(‘Request completed successfully.’); $(‘message-here’).setStyle(‘background’,'#fffea1′);
}
}).send();
});
});

Click here to receive a special message from a PHP script via a javascript alert.

Click here to populate the element below with the special message.

Special message will appear here.

Commenter Avatar March 18 / #
Sonal says:

I get the following error

[Exception... "'Permission denied to call method XMLHttpRequest.open' when calling method: [nsIDOMEventListener::handleEvent]” nsresult: “0×8057001e (NS_ERROR_XPC_JS_THREW_STRING)” location: “” data: no]

Commenter Avatar April 24 / #
David Pipes says:

I got this to work on a project i was working on. The only problem that i am having now is that i am calling to load a div with another jsp page. And nothing is loading correctly. Not loading the styles or the javascript form that page. Is their any way around this or am i taking the wrong approach.

Commenter Avatar April 27 / #
Gustavo says:

Hi David, i need use request.Html and Milkbox, can you help me? My code is:
$(‘ajax-replace_i’).addEvent(‘click’, function(event) {
event.stop();
var req = new Request.HTML({
method: ‘get’,
url: ‘http://localhost/toqueintimo/includes/verao_inf.php’,
data: { ‘do’ : ‘1′ },
update: $(‘thumbs’),
onRequest: function() { alert(‘Aguarde…’); },
onSuccess: function(response){
var milkbox2 = new Milkbox();
milkbox2.reloadGalleries();
alert(‘Milkbox…’);
},
onComplete: function(response) { alert(‘Request completed successfully.’);}
}).send();
});

Thanks,

Commenter Avatar June 03 / #
aurel says:

just last week i finished my first ever “application” that consisted of php and mootools, it was a guesbook format where the user had to add edit and delete comments

as it was the first time that i had used mootools or any javascript, the lectures managed to make it really hard for me to understand what the hell was going on,

and now here it is, an easy to understand intro to the way that MT and PHP can communicate together
now i MAY be able to redo ma assignment – a lot better

thanks for these cool tutorials

Commenter Avatar June 29 / #
PixelMaker says:

Hi,

Nice tutorial.

While implementing this, I stuck here: (I am using ‘accordion’)

I want to pass an unique ID with the request, so that i can grab some data associated with that ID thru PHP code (AJAX call).

Can you please let me know how to do that?

Thanks.

Commenter Avatar July 19 / #

Cool intro. Thanks!

Commenter Avatar December 31 / #
tsarma says:

Thanks a lot.

can the data contain more variables like
data : { ‘para2′ : ‘1′, ‘para2′ : ‘2′ }

Mootools Doc says data is a string, but you have an array. I would like to know more about the systex.
Regards

Commenter Avatar January 15 / #
Shashidhar says:

Hello john,
Hi how do you doing, my name is Shashidhar i am working on mootools, i want one help, I am working on customizing Firewall rules like Add, Edit and Delete rules from UI. i am sending data to back-end and processing it using python an rendering data back to front-end using Cherrypy template.render. Now i want to format data in JSON format and render it back to front-end in Asynchronous way how can i do that please suggest with code thanking you in advance.

Commenter Avatar February 08 / #
Saurabh Shukla says:

Hi,

You turn up on almost all solutions to problems I google! Thanks.

If I have a class initialized in domready like
ajaxer = new testClass(‘morelink’);
where morelink is the class of links
more
and such a link is present in multiple divs that I keep loading with your example;

I have come to understand that the class will not give love to this new content!

How do I make it do that?

I tried onSuccess, but I end up having multiple instance of this class.

Commenter Avatar February 08 / #
Saurabh Shukla says:

Sorry the link would be <a href=”something” class=”more” >

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2010. Contact David Walsh. Powered by the remarkable MooTools javascript framework.