How to Make AJAX Read between the Lines

JavaScript

Your site may contain a wealth of technical terms. The user while viewing it may have to wonder about their meaning. What can be done to provide site visitors with instant answers to the questions they have? Previously technical terms were represented as links so that users could click them and get a definition window. This approach, however, is rather clumsy and time-consuming: one has to click the link, wait for the definition window to load and then close it. Now with AJAX we can move closer to user’s expectations. We can make the message window appear instantly once the mouse is over the term and disappear when the mouse moves farther. This service will not affect the size of your web-pages. When the contextual help is required Java Script will get definition from an external dictionary and display it.

The method for getting information through an implicit request can be applied not only for technical dictionary. Have you ever wondered about the double underlined links in such projects as hotscripts.com and devarticles.com? This is context-dependent advertising based on IntelliTXT engine from Vibrant Media (www.vibrantmedia.com). When the mouse cursor points to such a link an advertisement window appears. This technology is referred to as in-text advertising.

This method is also increasingly used on news portals. The main page contains only the news headings. Yet when the user puts a mouse cursor over the heading a short description appears. Thus the main page can hold a lot more news. The visitor sees the headings and all he/she has to do to get a short summary is to browse through the items with a mouse cursor.

An example of using Thesaurus

Let us now look into how contextual help can be implemented with AJAX. Any developer familiar with this method will be able to make portal comment on news upon request or write an in-text advertising module.

Obviously, we have to think of a message window which will appear every time the user puts a cursor over the keyword. For the window to appear and disappear instantly it should be placed in a hidden DIV

To keep things simple we can make it look as a regular MS Windows system message

The window should appear the very instant user puts a cursor over it and disappear when the cursor is out. And at this moment the window should already contain the definition text, not a blank space. This means that we should place the terms in the document within an inline-tag that supports events onMouseOver and onMouseOut. The first event should be assigned a Java Script function which will get the term definition, place it into the window and display the window. The second event should be assigned a function which will simply hide the message window.

In the window displaying (getDefinition) function parameter we should specify the term. AJAX will use it to get the definition text. As we have to position the displayed window under the mouse cursor we should pass event parameter to this function to provide support of Gecko-based browsers. The hide message function (hideMessage) does not require any parameters.

Now our task is to make JavaScript position the message window when getDefinition function is called.

function adjustMessage(evt) {
	MessageObj = document.getElementById('InstantMessage');
	if (isThisMozilla) event=evt;
	var rightedge = document.body.clientWidth-event.clientX;
	var bottomedge = document.body.clientHeight-event.clientY;
	if (rightedge < MessageObj.offsetWidth)
		MessageObj.style.left = document.body.scrollLeft   event.clientX - MessageObj.offsetWidth;
	else
		MessageObj.style.left = document.body.scrollLeft   event.clientX;
	if (bottomedge < MessageObj.offsetHeight)
		MessageObj.style.top = document.body.scrollTop   event.clientY - MessageObj.offsetHeight;
	else
		MessageObj.style.top = document.body.scrollTop   event.clientY;

	MessageObj.innerHTML = 'Loading...'; 
	MessageObj.style.visibility = "visible";
}

Thus, we have a ‘data loading’ message window. Now we should request term definition from the controller. You can write your own AJAX (http://en.wikipedia.org/wiki/AJAX) request functions. Yet if you are new to AJAX I can recommend Yahoo library (http://developer.yahoo.com/yui/). In that case the request will look as follows:

function getDefinition(term,evt){
	adjustMessage(evt);
	var request = YAHOO.util.Connect.asyncRequest('POST', 'http://controller_address', callback, 'term=' term);
}

Clearly, we cannot request a controller we haven’t written. Generally, this is the simplest step. The controller’s task is to return term definition requested in POST. Whatever programming language you should use for this purpose, only a couple of basic operations are required:

  • connect to database
  • perform an SQL request to get the definition
  • display the result as follows:
{
"errormsg" : "error code in case of error",
"content" : "definition text"
}

This is a data format known as JSON. Java Script accepts it as a native declaration. In case you use Yahoo AJAX library the controller’s response is handled by the following construction:

var handleSuccess = function(o){
	if(o.responseText !== undefined){
		showMessage(o.responseText);
	}
};

var handleFailure = function(o){
	if(o.responseText !== undefined){
		showMessage("Connection Error");
	}
};

var callback =
{
	success:handleSuccess,
	failure:handleFailure,
	argument:['foo','bar']
};

The only thing left is to describe the showMessage() which puts the text received into the message window

function showMessage(json) {
var respondStructure = eval( '('   json   ')' ); 
MessageObj.innerHTML = respondStructure.content;
return false;
}

As you realize, to hide the message we only have to change object attribute

function hideMessage(){
var MessageObj=document.getElementById('InstantMessage');
MessageObj.style.visibility="hidden";
}

Trying this out you are unlikely to encounter any problems using MS IE. Yet, if you use FireFox, you might observe the message window flicker. This happens due to FireFox’s specific handling of onMouseOver/onMouseOut events. But this can easily be solved by putting delay flags into functions that handle these events.

The scripts from this example can be found at http://www.phpclasses.org/browse/package/3505.html