"There are only two industries that refer to their customers as "users"." - Edward Tufte

Getting started with Ajax - build your own smallest ajax framework

Ajax (Asynchronous JavaScript and XML) have drastically changed the way Web application work. Effective and controlled use of Ajax can make Web applications highly responsive. In this article, I will take you through the fundamentals of Ajax. We also build a small ajax library JavaScript file which can be used as the starting point for your projects.

Note that there are a lot of Ajax frameworks available such as DOJO and YUI. But one issue with these frameworks is that they are somewhat big. If your application has to work with a lot of dialup users, you will have optimize these frameworks. Also you will have to make use of tools such as YUI compressor.

So if you are just looking for simple Ajax functionalities such as refreshing a portion of a Web page, it is better to go with your own small Ajax framework.

Ajax as the term suggests enables us to retrieve content asynchronously over HTTP request. Along with DHTML you can use this to update selected sections of a Web page.

In order to use Ajax, you need to first get a JavaScript browser object called XMLHttpRequest. Using this you can make asynchronous HTTP requests. But the implementation of this object is unfortunately browser dependent! So our first task is to write a JavaScript function which returns XMLHttpRequest in a browser independent way. Let us call this function getXMLHttpRequest(),

function getXMLHttpRequest() {
      if (window.XMLHttpRequest) { 
         return new XMLHttpRequest();
      } else if (window.ActiveXObject) { 
         try {
            return new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               return new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      return null;
}

Now let us write a function which will use the XMLHttpRequest to do an HTTP GET request,

function getAjaxContent(url, callback) {
	var ajax_req = getXMLHttpRequest();
	ajax_req.onreadystatechange = callback;
	ajax_req.open('GET',url,true);
        ajax_req.send(null);
}

But where do we get the content of our Ajax request? The second argument to the getAjaxContent is a function pointer and this function will be invoked during Ajax execution. Remember - Ajax execution is asynchronous!

Now in our application we can use the above two methods for Ajax calls. Here is a sample which retrieves an RFC document using Ajax,

function getRFC22() {
   getAjaxContent("http://www.ietf.org/rfc/rfc0022.txt",cb); 
 
}
 
function cb() {
  if(this.readyState==4) {
      alert(this.responseText);
  }
}

If the URL you are accessing returns HTML, you will need to use this.responseXML instead of this.responseText

April 30, 2008 | Posted in Ajax | No Comments »

Implementing pagination at database level (Oracle SQL) - Use RANK

It is a common requirement to have pagination in Web applications. The easy way is to query all the records and then apply pagination logic to the data in memory. But this approach won’t work with tables which contains huge data sets.

The best approach is to do the pagination at database level using SQL. Database technology is an old and mature technology and hence this method is the most efficient one.

For example, let us assume that our application contains a CUSTOMER table and we want to display 15 customers at a time in a table. In Oracle, you can write a query like this one,

SELECT * FROM (SELECT C.*,ROWNUM AS R FROM CUSTOMER C) WHERE R > 0 AND R < 10

But what if you want to sort the customer data on the customer name and then want to display the first 10 records?

SELECT * FROM (SELECT C.*,ROWNUM AS R FROM CUSTOMER C ORDER BY CUSTNAME) WHERE R > 0 AND R < 10 

But if you check the results, you will be in for a shock. The data will be wrong. This is because Oracle first applies the ROWNUM limit and then applies sorting on the limited set! So how do we get the first 10 customer after sorting on the customer name? That is where the analytical function RANK() comes to the rescue!

SELECT * FROM (SELECT C.*, (RANK() OVER (ORDER BY CUSTNAME)) AS RN FROM CUSTOMER C)
WHERE RN > 0 AND RN < 10

This approach doesn’t work in databases where there is no built RANK() function. For example, on AS400 systems only way to sort is to navigate to the required data window and then return only the records required. If you want records between 10 and 20, do a query and then navigate from 1 to 10, ignore records and then navigate from 10 to 20 and then break out of the query. But for large data sets navigating to the last page will take a lot of time.

April 29, 2008 | Posted in SQL | No Comments »

How do I execute scripts in the content retrieved using Ajax?

Ajax enables Web application developers to build highly responsive Web interfaces. Ajax also comes with a lot headaches. One such problem arises when the content returned by an Ajax call contains JavaScript. By default this script won’t be executed by the browser and any JavaScript functions in the Ajax content won’t be available to the main page.

So how to execute JavaScript in the Ajax content?

When you use Ajax, you first make an asynchronous call to server and the content returned is then assigned to a div tag using the innerHTML property as shown below.

document.getElementById("divId").innerHTML = ajaxContent;

In order to execute scripts inside the variable “ajaxContent”, we need to extract the script blocks and then pass to the JavaScript engine. So we will rewrite the above as follows,

setAjaxContent("divId", ajaxContent);

Here is the pseudocode for the setAjaxContent method,

1. Extract JavaScript method block by scanning for <script> tag.

2. Pass the JavaScript method block to browser JS engine by calling eval method.

3. Set the Ajax content to the div tag using innerHTML property.

function setAjaxContent(divId, html) { 
  var temp = html;
  while(true) {
    var sindex = temp.indexOf("<script"+">");
    if(sindex < 0) break;
    var eindex = temp.indexOf("</"+"script>",sindex);
    var js = temp.substring(sindex+8,eindex);           
    eval(js);
    temp = temp.substring(eindex+9);
  }     
  document.getElementById(divId).innerHTML=html; 
}

The above code scans for <script> blocks and then passes the script block to JavaScript engine using eval(). Finally the content is added to the innerHTML of the div you want to refresh.

This assumes that all the JavaScript’s in the content retrieved by Ajax is inside <script> and </script> tags (without spaces or other attributes). For example, you will have to modify the function if you have the starting script tag as <script type=”text/javascript” >.

April 27, 2008 | Posted in JavaScript | No Comments »

Creating a Website menu using unordered list and CSS

Top level horizontal menus can be seen on a lot of Websites. Wondering how to quickly create one for your own site? If you are a theme developer(wordpress,joomla, drupal etc.), you will come across this need very frequently. There are many options to create horizontal menus, but the easiest and the most HTML friendly way is to use HTML unordered list (UL tag) and CSS. In this post I will show you how easy it is to create a menu using UL tag and CSS.

1. As the first step create a menu structure using UL and LI tags - The following HTML code defines a sample menu structure. Note that the default UL behaviour is to list items vertically with bullets.

ul menu stage1

<html>
<body>
<ul>
  <li><a href="#">Home</a>
  <li><a href="#">Subscribe</a>
  <li><a href="#">About</a>
  <li><a href="#">Contact</a>
</li></ul>
</body>
</html>

2. Covert the menu to horizontal form - Before we can convert the ul/li tags to the horizontal form, we need to attach styles to it. In this case, I have enclosed the UL/LI in a div with class "menu". You can then apply CSS to the styles as given below. As you can see it requires just 2 style attributes to change the menu to horizontal form.

creating html menus using css2

<html>
<style>
.menu ul li { list-style:none;display:inline;}
</style>
<body>
<div class="menu">
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Subscribe</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
</ul>
</div>
</body>
</html>

3. Add styles for links in the menu - Now we need to convert the links to look like a menu. The idea here is to increase the padding of anchor tag and then apply a different style when the mouse hovers over the link. We first apply float property on LI to remove unnecessary padding and to make it look like a menu. Then we apply disply:block to the anchor tag inside LI. The anchor tag will now occupy the complete space inside LI tag. We then add padding to the anchor tag to bring adequate space between menu items. Also anchor background color is changed when mouse hovers over the link. Here is it in action,
website menu using html and css3

<html>
<style>
.menu ul li { list-style:none;display:inline;float:left;}
.menu ul li a {padding:10px;background-color:blue;
      display:block;color:white;text-decoration:none;}
.menu ul li a:hover 
      {padding:10px;background-color:black;}
</style>
<body>
<div class="menu">
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Subscribe</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
</ul>
</div>
</body>
</html>

4. Use images in the background for better visual effects - The menu is now complete. But you can give better visual effects if you use images instead of direct color codes for the background. Check out the following example which uses images for anchor backgrounds. In the hands of an expert Web designer the background images alone can create exceptional effects!

website menu last preview

<html>
<style>
.menu ul li { list-style:none;display:inline;float:left;}
.menu ul li a 
   {padding:10px;background:url(bg.png);display:block;
   color:#990000;text-decoration:none;font-weight:bold;}
.menu ul li a:hover 
   {padding:10px;background:url(none) black;}
 
</style>
<body>
<div class="menu">
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Subscribe</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
</ul>
</div>
</body>
</html>
April 26, 2008 | Posted in CSS | No Comments »

Confirm closing of browser window using onbeforeunload

While using a Web application, users may accidently close the browser by clicking on "close button". For application windows which are used for extensive data capture, it is better to provide a confirmation message before the browser is closed. This is where onbeforeunload event of body/window object can be used.

An event handler JavaScript function can be assigned to onbeforeunload event. If a value is returned from this function, browser will ask for a standard confirmation message. The returned value will also be displayed in this confirmation message. Consider the following HTML page,

<html>
<body>
	<script>
	function preventClose() {
		return "Message from onbeforeunload handler";
	}
	window.onbeforeunload = preventClose;
	</script>
</body>
</html>

onbeforeunload confirmation message

When you try to close browser window with the above html file loaded, you will get the confirmation message shown on the right.

But there is a problem here. If your page has anchor tags with JavaScript method attached to href, onbeforeunload is called even before executing the href script! This is because browser considers href navigation as moving to a different page. For example clicking on the link given below triggers onbeforeunload,

<a href="javascript:onSave()">Save</a>

The solution in this case is to attach JavaScript to an anchor tag using onclick() event. Here is an example,

<a onclick="onSave()" href="#">Save</a>

This won’t trigger a onbeforeunload unless you submit form or navigate to another page from the onSave() method.

April 25, 2008 | Posted in JavaScript | No Comments »