Skip navigation

Blog > Mootools and Ajax features

Ajax is a method used in web applications to enable the retrieval of data from a server asynchronously in the background without interfering with the display and behavior of the existing page. This can be extremely useful in web software as it allows the user to interact with a web page without the page having to reload.

Ajax uses a few technologies one of them being JavaScript which is where MooTools comes in. At Bluelinemedia we use the MooTools framework as described in the following blog, How we use Javascript.

Using Ajax with MooTools allows for a much simplier development of Ajax.

An example of how to use Ajax with MooTools is below.

1. Firstly you need to add a blank div onto a page, this is where the Ajax will insert the content it creates. I have also added a link, when clicked this will activate the Ajax functionality. This page will need to be linked to the MooTools JavaScript files.

<code><a href="#" title="" class="testlink">Click Me</a>

<div id="ajaxdata"></div></code>

2. Then you need to create a page that will print the content you want through using Ajax. In this case l will just display a simple text statement but this page could have various function calls in it.

<code><p>hello world</p></code>

3. Now for the MooTools part. I will presume you have MooTools already setup correctly. Firstly add a new function call to the window add event.

<code>

window.addEvent('domready', function()
{
ApplyTestAjax();
}

</code>

Then create this function you just added. This will test whether the link exists in the page and if it does it will add an 'on click' event to it. Whenever that link is clicked on it will run the RequestTestData function. The variable we add to the RequestTestData call is to the page that stores the Ajax data, in this case ajax.php.

<code>

function ApplyTestAjax()
{

aTestLink = $$('a.testlink');

if(aTestLink.length > 0) // Test whether the link exists in the page
{

// Add an on click event to the link
aTestLink.addEvent('click', function() {
return RequestTestData('ajax.php');
});
}
}

</code>

Finally we add the RequestTestData function. This is made very easy due to using MooTools. We tell the script what url to call, what div to update and finally what to do once this update has been completed. For this example l have set the colour of the text to red upon completion just to give you an idea of what could be achieved.

<code>

function RequestTestData(aUrl)
{
new Request.HTML({
url: aUrl, // Call this
update: $('ajaxdata'), // Update this with the results
onSuccess: function(response)
{
$('ajaxdata').setStyle('color', 'red'); // Changes the text colour to red
}
}).post({});

return false;
}

</code>

Hopefully that will give you a quick insight into how you can use MooTools and Ajax together to improve the usability of your web application.