DWRequest: MooTools 1.2 AJAX Listener & Message Display

By  on  

Though MooTools 1.2 is in its second beta stage, its basic syntax and theory changes have been hashed out. The JavaScript library continues to improve and become more flexible.

Fellow DZone Zone Leader Boyan Kostadinov wrote a very useful article detailing how you can add a Gmail-like AJAX display to your website using the Prototype JavaScript library. The article got me to thinking: could it be helpful to always display an AJAX notification message upon every request's initial request, success event, and failure event? Maybe even only for debugging purposes?

Whatever your reason may be, I've created the DWRequest MooTools class to inform the user or developer of each AJAX request and subsequent result.

The CSS Code

#message	{ display:none; width:150px; text-align:center; padding:5px 8px; font-weight:bold; position:absolute; right:2%; font:12px arial; }

The XHTML Code

The following code is an example of two XHTML links that make AJAX calls. Note the message DIV.

<body>

	<div id="message">Performing Request...</div>
	<a href="inputs.php" class="ajax">Succeed</a><br />
	<a href="sug.php" class="ajax">Fail</a>

</body>

The MooTools JavaScript Code

var DWRequest = new Class({
	Extends: Request,
	options: {
		onRequest: function() {
			show_ajax_message('request');
		},
		onSuccess: function() {
			show_ajax_message('success');
		},
		onFailure: function() {
			show_ajax_message('failure');
		},
		onCancel: function() {
			show_ajax_message('cancel');
		}
	}
});

//adds initial events
window.addEvent('domready',function() {

	//for every action class
	$$('.ajax').each(function(el) {

		//add an event..
		el.addEvent('click', function(e) {
			e = new Event(e).stop();

			//make ajax request
			var req = new DWRequest({
				url: el.get('href'),
				method: 'get',
				data: 'something'
			}).send();
		});
	});
});

//shows the block
function show_ajax_message(state)
{
	//set position
	$('message').setStyle('top',window.getScrollTop() + 10);

	//on request...
	if(state == 'request')
	{
		//show the box
		$('message').addClass('onrequest').setText('Performing Request...').setStyles({'background-color':'#fffea1','display':'block','opacity':'100'});
	}
	//on success
	else if(state == 'success')
	{
		//take care of box
		$('message').set('text','Request Complete!');

		//do effect
		var myMorph = new Fx.Morph('message',{'duration':1000});
		myMorph.start({'opacity': 0,'background-color': '#90ee90'});
	}
	else if(state == 'failure')
	{
		//take care of box
		$('message').set('text','Request Failed!');

		//do effect
		var myMorph = new Fx.Morph('message',{'duration':1000});
		myMorph.start({'opacity': 0,'background-color': '#ff0000'});
	}
	else if(state == 'cancel')
	{
		//take care of box
		$('message').set('text','Request Cancelled!');

		//do effect
		var myMorph = new Fx.Morph('message',{'duration':1000});
		myMorph.start({'opacity': 0,'background-color': '#fffea1'});
	}
}

The Explanation

  1. Once the DOM is ready, any link with the class ajax is listened to -- upon click, a DWRequest class instance is created.
  2. I've extended the MooTools Request class, adding default actions for the onRequest, onFailure, onCancel, and onComplete events. (Calls the show_ajax_message() function.)
  3. The function displays and manipulates the message DIV as needed: color morphing, message changes, and positioning.

Do you have any suggestions for my class? Please share!

Recent Features

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

Discussion

  1. Great little script!

    The only thing I’d add is more information about the faillure message. Like wich type is it. Because that’s meaningfull if it’s used for debugging.

    Also it can be “extended” by shooting the php error message in the postback nad showing it in the message box, like… this value is missing or inexistant, etc. depending on which type of request you’ve fired, but that’s getting a bit out of the js part ;).

    gj!

  2. Thank you for your ideas Keven!

    In terms of versioning, I guess I’d consider this a “0.1”. I hope to continue working on this class, adding user-friendly icons and providing more information about the Ajax request itself (displaying url, execution time, …)

  3. Use switch statement instead of the if, it is more appropriate here and the performance is better.

    Why you have called it *DW*Request? what is the meaning?

  4. Right nir, I’ll incorporate a switch next time. The “DW” is simply my attempt at tracking usage (my initials).

  5. Wouldn’t it be more mootoolesk to add the function show_ajax_message to the class, cause there is no other one that will use it.

  6. @Andreas: Absolutely. After I published the article, I kicked myself for not doing that. I’ll do that in the next version.

    @All: Any more suggestions?

  7. Fabrice Terrasson

    Tried to extend Request.HTML without success. Any clue ?

  8. acctman

    do you have any examples or tips for using this to display a notification to a user? Pretty much what I want to do is if the user is on the site, and i need to send out a notification to all users, how would i call the Request… ? is there anyway to do this, what method would work without having the user to reload a page to see the message. I.e. in a chat room

  9. Cheers David,

    http://paste.davidwalsh.name/78

    I’m using your code in my Ajax-based-Joomla.
    Actually, it’s highly modified as I’ve made a simple generic class.

    Hope you don’t mind to take look in your pastebin area.

    Thank You. Thank You. Thank You.
    note: pastebin looks great… I’ve never known you have it.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!