AJAX TECHNOLOGY

To create custom dynamic web applications a programmer must utilize Ajax. Ajax is a group of technologies that provide asynchronous two-way communication between a server and the web browser. Asynchronous communication allows the user to continue to browse the web page as sections of it are being loaded. This also allows the page to display new and updated information with out refreshing the page.Ajax development has exploded in recent years as companies have found customers prefer pages developed with it.
ESPN uses Ajax extensively on their website to refresh scores and provide news headlines without the user having to update the page.
                        Creating an Ajax request requires three sections of code, the first section is writing in HTML, the second writing in JavaScript and the third is a server script writing PHP. Each section of code provides a different portion of the Ajax request, if the request is missing any of the sections it will fail.  While Ajax is good for many scenarios a programmer must carefully examine its use to prevent problems from arising.
                       AJAX is a relatively new method to create rich internet applications with responsive interfaces that allow the designer to take a lot of the tedium out of using web-based mediums for day-to-day data interaction.  The scope of this paper will be to provide information about what AJAX is and what it does, when it should and shouldn’t be used and what the future looks like for AJAX in comparison to the present and future alternatives.  This will help developers determine the value of using AJAX in their projects and provide information about the proper use of this technology.  This report will assume a basic knowledge with web forms and the design of web applications.
AJAX is an acronym for Asynchronous JavaScript and XML.  It is not a technology in itself, but rather a suite of technologies.  The combination of JavaScript and XML allows for a responsive user interface.  It requires more development time than a traditional web solution; however a well-designed AJAX user interface makes the traditional form-based web application seem almost archaic.
                The technologies powering the internet are changing at an accelerated rate; one of these technologies is Ajax. Ajax or Asynchronous JavaScript and XML are a group of technologies that provide a rich web development platform. Jesse James Garrett introduced the term Ajax in February of 2005 to describe a new method of programming using readily available technologies. Ajax requires four distinct components to provide a rich user interface. The components are JavaScript, XML, HTML, and CSS.
      Ajax is unique because it allows for the creation of desktop like applications in a web environment. Typically a “desktop” application is very responsive and can have sections of the program change without refreshing the entire screen. This occurs because the program is running on the local machine. Web applications usually run thru an internet browser like Microsoft Internet Explorer or Mozilla Firefox.  These applications are usually slower because they require the server to process each request. Most web applications require the entire webpage to be processed at once. This means when a user clicks on a link in a webpage the whole page will be changed. With Ajax a user can click on a link and have a section of the page recreated for them without changing the whole page. This removes a portion of the load from the server because it only has to parse a section of the page rather than the whole page.
 
What is AJAX and what does it do?

As mentioned in the introduction, AJAX is a suite of technologies used to create rich internet applications.  It uses JavaScript to gather and show data to the user.  It uses XML transmitted either in the XMLHTTPRequest or IFrame objects to communicate with the server.  Together they allow the user to do a lot of things interactively with one web page.  The diagram illustrates on which side of the data transaction XML and JavaScript function.

            As opposed to traditional form-based interaction, in an AJAX application, JavaScript provides a lot of the interaction.  While elements of web-forms are often used, in well-designed AJAX, JavaScript becomes the medium for interaction and the web page only provides the layout for the data and the way it will be displayed.  JavaScript is in charge of the input and output events and displaying the data associated with those events.  This allows one web page to display and manipulate a lot of data without having to be reloaded.           
While JavaScript can manage the user interface, it cannot communicate with the server.  This is where XML comes into play.  This paper will discuss XML but any method of conveying data can be used if the situation requires it.  XML serves as the communication between the web page and the server.  This makes a compact response object because the server only has to send an XML object representing the data that will be displayed in the web page already in the browser.  By creating a smaller response object and putting some of the processing associated with display on the client computer, resources from the server are saved.  Finally, since the client doesn’t need to load a new page, the data is displayed much quicker, creating a much faster interface that is much more enriching for the user.

            It’s not hard to see how many applications this would have.  A great example would be a form that allows users to look at their email.  In the traditional web form model, a user would have to view a new web page every time they wanted to cycle to a new email.  Using an AJAX web application, the user could cycle through emails without ever having to load a new web page.  This is an example of a simple AJAX application although it could go so far as to implement a menu to select which email to view, a way to create and send emails, and a method of instantly notifying a user of new emails into the same web page, never having to be refreshed.  Obviously, this would create a faster and more responsive web experience.
                 
ORGINS OF AJAX

        Even though Ajax wasn’t formally defined until February of 2005 the first Ajax type web application was released in 2000 by Microsoft for use with Outlook. Microsoft was looking to create a web based version of its popular email client that did not require the page to be refreshed to notify the user a new email had arrived. Microsoft created the XMLHttpRequest object which became the basis for Ajax traffic. The XMLHttpRequest allows a client computer to call a webpage in the background without interfering with the user. This type of transfer is called asynchronous because it passively waits for the server to respond. This is the first component in Ajax and is usually called thru JavaScript.
      Using the XMLHttpRequest data can be gathered from the server. To update the webpage to show this new data Dynamic HTML must be used. Dynamic HTML uses CSS, HTML and JavaScript to rewrite sections of the webpage code at the browser instead of regenerating the page on the server.
      The term Ajax became widely known after the release of Google Maps and Google Suggest. These products showed flexibility never before seen in a web application and thus spurred developers to make new and innovative applications.
                               
A time and a place…

            With all of this power, why not use AJAX for everything a webpage does?  Since all AJAX provides is a method of synchronizing and transferring data on request from the user and then manipulating it into the display, it shouldn’t be used for everything.  While it may be tempting to create a web site that uses AJAX to provide on-the-fly search functionality and customizable navigation, AJAX development takes a lot of time, and the charm it provides will quickly wear off.  Here are some situations where the development of an AJAX solution will provide the maximum return from development costs.

Forms:  There is nothing more tedious than having to use the traditional web-form method for data entry.  By applying AJAX to web forms, an amazing amount of functionality is added.  Imagine being able to create a Windows application style interface to receive information from users on the web.  When compared to a standard web interface, this seems much better.  AJAX in forms has an obvious use anywhere multiple instances of the same data type will be received or displayed.  It can also be used where modifying information will change information somewhere else to provide real-time updates.


Rapid Interaction:  AJAX allows a web page to be used to create rapid interaction with the user.  AJAX can make instant messaging on a web page a reality.  AJAX can be used to allow a web page to serve as an event-based alarm, such as a stock ticker that warns the user when a price is reached.  AJAX can be used in any situation where a browser is typically auto-refreshed which is another way AJAX moves the functionality in creating web applications closer to the freedom had when creating Windows applications.

Avoiding Refreshing:  AJAX should be used in any situation that requires a lot of browser refreshing.  Loading large lists for several small manipulations or working through a long tree view on a forum are tedious examples of situations where traditional web solutions spend a lot of time refreshing.  Filling out small request or voting form on the side of a larger feature is so slow and distracting users avoid doing it.  AJAX provides an elegant solution to all of these problems by being able completely avoid browser refreshing.

Auto Complete:  This is tricky situation.  AJAX can provide a great solution here when it provides auto completion of things that are similar between many users or a situation where users would use different language to describe the same thing.  However, the time spent developing something like this for a website may just end up overlapping functionality already provided by most major browsers.  If done correctly however, using AJAX to provide a well placed auto completion text box is a great idea, the key is to make sure that major browser’s auto-complete functionality isn’t duplicated and that the auto-completion being provided is worth the time to develop it. 

AJAX has a fairly slow development time and it is in a developer’s best interest to use it only where it will provide a benefit that is worth the extra development time.  For example, using AJAX to manage the navigation on a website is overkill.  Using the DOM, CSS and XHTML is an easier and faster way to develop this.  As outlined before, typically AJAX shouldn’t be used to provide the shape of the interface, but should be used to handle the interaction between the Client and the Server with the web page as the middle ground.

AJAX EXAMPLE

        A trivial example of Ajax is a name retrieval service.  The script will suggest names matching the letters entered into the box without requiring the page to be refreshed. If the script was written without Ajax after each letter entered, the page would need to be refreshed. This would create excess load on the web server and be distracting to the user.


HTML CODE

        Code Sample 1 shows the HTML code that generates the form. The code is standard hypertext markup language (HTML) with a few additions. The first addition is the clienthint.js which holds the Ajax calls and declares a function called showHint(). To make the script notify the user of new suggestions on each key stroke the input section of the form has the following code added onkeyup=”showHint(this.value)”. This piece of code makes the web browser call showHint every time the user releases a key in the field. The final portion of code required is <span id=”txtHint”></span> this labels a section of the code as txtHint. This label will be used later to output the result of the Ajax query.

<html>
<head>
<script src="clienthint.js"></script>
</head><body><form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)"
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Code Sample 1

        Code Sample 1 produces an output similar to Figure 1 in web browser.  The form will not work until the clientthint.js is created. This file will define the function showHint and perform the XMLHttpRequest to the server.

JAVASCRIPT CODE

        The JavaScript code (clientthint.js) consists of three functions and a global variable. The global variable is defined as an XMLHttpRequest and is named xmlHttp. The xmlHttp can be defined with the following line of code var xmlHttp.  The three functions are showHint, stateChanged and GetXmlHttpObject.

FUNCTION showHint()

        The function showHint is the driver function of the JavaScript. The function takes the string inputted in the form and creates the request to the server. The function also tells the computer to call stateChanged when the request to the server has completed.  Function showHint is shown in Code Sample 2. The first line of showHint defines the variable xmlHttp as an XmlHttpRequest by calling the GetXMLHttpObject function.  The second line defines a variable named url which contains the location of the server side script. Url is also defined with two parameters q and sid. The q parameter represents the string being sent to the server, the sid parameter is used only to make each request unique.If the sid parameter was not given the web browser may not call the server script and use a cached copy instead.
      The next three lines setup the XmlHttpRequest parameters and perform the actual request. Setting onreadystatechange to the function stateChanged forces the web browser to call stateChanged when the request has completed. The call to function open sets the request to use the ‘Get’ method to call the script located at variable url. The third parameter defines whether the request will be synchronous or asynchronous.By passing the parameter of true the request is set to an asynchronous mode. The final step in the function is to call the send method. Send executes the request and ends the showHint function.

function showHint(str)
{
      xmlHttp=GetXmlHttpObject()
      var url="getsug.php?q="
            +str+"&sid="+Math.random()
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET",url,true)
      xmlHttp.send(null)
     
}












Code Sample 2

FUNCTION stateChanged()

        This function processes changes in the state of the xml request. The function first checks if the readyState is equal to 4. The readyState changes based on the current status of the xml request. A status of 4 indicates the request is finished and the server’s response is stored in responseText.If the status is 4, the server’s response is outputted in the section labeled txtHint. The function stateChanged in shown in Code Sample 3.

function stateChanged()
{
      if(xmlHttp.readyState==4)
      {
      document.getElementById("txtHint").innerHTML=xmlHttp.responseText
      }
}
Code Sample 3

FUNCTION GetXmlHttpObject()

        The function GetXmlHttpObject creates an XMLHttpRequest based on which browser is used. The function returns a valid XMLHttpRequest. The first line of the function creates a temporary variable.  The first if statement checks to see if the browser supports window.XMLHttpRequest, if the browser does support it then the variable is initialized to a new XMLHttpRequest.  The second if statement is only used when the previous check fails. This statement checks if an ActiveX object exists. If the object exists then the xml request is defined using ActiveX. The final step is to return the object that was created. The function GetXmlHttpObject is shown in Code Sample 4.


function GetXmlHttpObject()
{
      var objXMLHttp=null
      if (window.XMLHttpRequest)
      {
            objXMLHttp=new XMLHttpRequest()
      }
      else
            if (window.ActiveXObject)
            {
                        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
            }
      return objXMLHttp
}

Code Sample 4
SERVER SCRIPT

        The server script is the last section needed to make the example work properly. The server script takes input as part of the url and displays the output in text. Simply put the server script is merely a webpage. For the example, the server script will be programmed in PHP an open source scripting language. The script should use the name that was defined in the JavaScript url of Code Sample 2.
      The first part of the script is to define the list of words to match the input against. This list can be changed on the fly without the user having to refresh there webpage.  The next step is to take the input which is stored in $_GET [‘q’] and store it in a temporary variable named q. The next section of code takes the input string and compares it against each entry listed in the word list. Each entry that matches is concatenated on the hint variable. If no entries are found the server’s response is “no suggestions”. If a hint is found but the hint is not the word typed in, the hint is returned in bolded letters. If the hint is the word typed in then the response is html code to output “we have got a match” in big red letters. The final step of the server script is to output the response that was generated. The server script is displayed in Code Sample 5.

<?php
// Fill up array with names
$a[]="Greg";
$a[]="Fran";
$a[]="Stacey";
$q=$_GET["q"];
for($i=0; $i<count($a); $i++)
 if(strtolower($q)==strtolower
(substr($a[$i],0,strlen($q))))
    if ($hint=="")
          $hint=$a[$i];
    else
          $hint=$hint.", ".$a[$i];
if ($hint == "")
     $response="no suggestion";
else
      if(strtolower($hint)==strtolower($q))
            $response="<font face=\"Verdana\" size=\"24\" color=\"red\"><b>".$hint."<--We got a match</b></font>";
      else
            $response="<b>".$hint."</b>";
echo $response; //output the response
?>
Code Sample 5


AJAX’s ROLE

AJAX’s Role Now and in the Future:
While AJAX provides the most compatible solution to the problem of how to provide fast and flexible interaction with the user, it is not the only solution available.  Macromedia’s Flash plug-in allows a lot of freedom in user interface creation.  So do Java applets.  Java applets also allow for complex server communications.  Comparing AJAX to other solutions, which this section attempts to do, shows the major strength of AJAX is compatibility, but it isn’t as flexible as other solutions.
            The first solution typically used to create an enhanced user interface is Macromedia Flash.  Flash requires a browser plug-in distributed by Macromedia who is now a subsidiary of Adobe and is in the process of re-branding.  The fact a plug-in needs to be installed immediately creates some distrust from a substantial amount of users.  Coupled with the very distinct look Flash sites have, it has lead to Flash being almost taboo to use in corporate web design.  Some users also describe it as tacky or cliché.  Asking whether or not to use Flash is bound to elicit a strong opinion from nearly any web designer.
            A good Flash designer is usually hard to find.  While it is easy to learn to create Flash sites, it isn’t always an intuitive process.  It takes a big skill set, consisting of animation, graphics design, web editing, object, artistic creativity and script programming in a proprietary language.  To add to the grab-bag of skills required, Flash can be used in tandem with XML in a technique known as AFLAX.  This provides the same server communication advantage that AJAX provides, but also allows the expanded user interface of Flash.  The new Flash development suite, Flex, should allow for this to be done more easily.  Ultimately, Flash is a good product that some would say is good at lights and smoke, while others would say is great at providing the stage to perform on.  It is up to the designer to decide if it’s right for the job.
            Another solution that certainly provides all the functionality AJAX does is Java applets.  Java applets provide desktop functionality in a web page.  They are basically an executable that is ran and displayed in a web page container.  While making them is similar to creating a desktop application, there are some differences.  The program is ultimately an application on the client machine but much of the data comes from the server.  It requires a weighty framework to operate and it cannot readily access many of the client system’s resources.  Java applets are slow to load usually, but once they are running they’re very fast.  They are probably overkill in situations where AJAX can be used, but they provide one-of-a-kind functionality for programs that display a lot of variables in real-time.  They are also often used in creating interactive games on the web.  Java applets also are a security concern to most IT professionals therefore they are not allowed on a significant number of workstations, making compatibility a large concern.
            Those are the two major existing alternatives to AJAX.  There are several alternatives that aren’t in wide-implementation yet, because of browser dependence or because they are still in development.
            XUL is Mozilla’s attempt to create a highly functional markup language.  It allows for fairly sophisticated user interfaces, but its lack of flexibility has some developers finding insurmountable obstacles in designing complex web applications.  It only operates on Mozilla based browsers.
            XAML is Microsoft’s attempt to create a highly functional markup language.  It is still in development and is slated to be released with Windows Vista.  While it is functionally an answer to AJAX it is exciting with Microsoft’s current trend toward rapid application development tools to think that AJAX’s functionality could be provided with lower development costs.  While it will certainly be more functional and configurable than XUL, it will also be dependent on WinFX meaning it won’t work on browsers that don’t use Avalon.
            SVG stands for Scalable Vector Graphics.  The standard for SVG is being developed by the W3C but is very slowly being integrated into browsers.  SVG uses XML to describe 2-dimensional vector graphics.  If SVG becomes integrated like other W3C technologies have, then it will provide a default standard for complex graphics in web browsers and in tandem with JavaScript it will provide all of the functionality that Flash does.  Since it is an addition to the DOM it will be more of a partner to AJAX than a replacement, but is important to look at regardless.
            That gives a lot of options for expanded user interfaces in web applications.  Choosing the method used isn’t usually a tough decision.  It’s often based on the preference of the designer.  However, some critical thinking should be made before a decision is made based simply on the preference of the designer.
            AJAX requires a lot of time to develop however the skills used to develop AJAX are common place amongst web developers.  Learning to apply JavaScript and XML together doesn’t take a tremendous amount of time to learn.  Java Applets and Flash require specialized developers but developing the solution in them can be cheaper.  XUL, XAML and SVG require an even rarer skill set, but XUL and XAML provide the fastest development time.  After considering development costs, compatibility becomes the main concern.
            AJAX is native to most modern browsers.  Technically, Internet Explorer requires a plug-in to use AJAX, but its installation and use is transparent to the novice end user.  Flash and java applets both require plug-ins to operate.  Some users don’t want to install plug-ins or some administrators don’t allow them.  XUL and XAML are both browser dependent.  While XAML will have the larger market share, XUL has a small but vocal user base that is substantial to commercial sites.  SVG currently has a very tiny user base.
            It is likely that AJAX is going to be with us for a while.  While alternatives exist today, nothing can really do what it does.  Developing for AJAX now is a good idea.  Flash is currently the most viable alternative, but with new, promising technologies being released, Flash stands to see some of its market share cut.  Java applets are becoming less and less common place.  Out of the newest crop of alternatives, XUL, XAML and SVG, XAML appears to be the most promising in functionality and will likely have the broadest user base, but as SVG is implemented into major browsers, its potential is being show.  XUL, only being compatible with a small share of browsers and lacking any significant development base in web applications, falls behind and shouldn’t be used in the development of web applications under normal circumstances.

               
AJAX IN .NET
Ajax in .Net Technology:
                              Asynchronous JavaScript and XML (AJAX) has recently become the craze thanks, in no small part, to Google’s usage of it in Google Suggest as well as Google Maps.  In ASP.Net terms, AJAX allows server-side processing to occur without requiring postback, thus enabling clients (browsers) with rich server-side capabilities.  In other words it provides a framework for asynchronously dispatching and processing requests and responses from the server. AJAX leverages a number of existing technologies, which aren't particularly new, however fondness for what these technologies have to offer (collectively, they are AJAX) has recently soared.

Enter Michael Schwarz's AJAX .Net wrapper which allows ASP.Net developers to quickly and easily deploy pages capable of easily capitalizing on AJAX.  Users should be cautioned that the wrapper is early in development, and as such isn't fully matured. 

It should be pointed out that technologies such as AJAX are very likely going to lead to violations of layered architectures (N-Tier).  My opinion is that AJAX increases the likelihood that the presentation logic layer (or worse, the business layer) will leak into the presentation layer.  Strict architects, like me, might cringe at this notion.  I feel that even if AJAX is used in a manner which slightly violates layer boundaries, the payoffs are well worth it. Of course, that's something you'll need to look at for your specific project and environment.

How it works - Overview

             AJAX relies on a broker to dispatch and process requests to and from the server.  For this task, the .Net wrapper relies on the client-side XmlHttpRequest object. The XmlHttpRequest object is well supported by most browsers, making it the solution of choice.  Since the goal of the wrapper is to hide the implementation of XmlHttpRequest, we'll forgo any detailed discussion about it.
              The wrapper itself works by marking .Net functions as AJAX methods.  Once marked, AJAX creates corresponding JavaScript functions which can be called client-side (liky any JavaScript functions) and that serve as proxies, using XmlHttpRequest.  These proxies map back to the server-side function.
               Complicated?  It isn't.  Let's look at a simplified example.  Given the .Net function:

'VB.Net
public function Add(firstNumber as integer, secondNumber as integer) as integer
  return firstNumber + secondNumber
end sub

//C#
public int Add(int firstNumber, int secondNumber)
{
   return firstNumber + secondNumber;
}

The AJAX .Net wrapper will automatically create a JavaScript function called "Add" which takes two parameters.  When this function is called using JavaScript (on the client), the request will be passed to the server and the return value back to the client. 


SAMPLE OUTPUT

        The example presented will now operate properly if each of the files is placed on a web server. As text is entered into the First name field the suggestions box will change. A sample output is shown in Figure 2 and 

AJAX BENEFITS
                                                                                         
        The main benefit of the Ajax suite is its ability to provide a robust interactive web application. Ajax also removes the time the user spends waiting on a web page because the page can be loaded in sections. Ajax is used in areas where large amounts of data need to be available to the user quickly but without the user having to wait for a new page to load. An example of this scenario is a calendar. The calendar will show all events but when the user moves their mouse over an event an Ajax call could load information on the particular event. This reduces the load on the server and the amount of traffic sent each time a user requests the calendar. Instead of sending the user the calendar and the information on each event when the page is loaded the user would only receive the calendar and the information about each event would be loaded as the user requests it.
      The XMLHttpRequest was designed using a sandbox model. This means the XMLHttpRequest runs in a locked down mode where it can only access websites that are located on the same domain as the script it was called from. This prevents Ajax from being used in cross-site-scripting.

AJAX PROBLEMS/ISSUES

        Ajax can provide rich web applications but if used improperly can create a security nightmare. One issue with Ajax is that if the browser denies the Ajax request for any reason the users application loses all functionality. The second issue involves executing malicious code.  Developers often “clean” the input they are sending to the server. The input must be “cleaned” to prevent the server from accidentally executing a command an attacker tries to run.With Ajax it’s tempting to clean the input on the client side using JavaScript and then not clean it on the server side. The problem with this is an attacker could call the server script without using the client script and compromise the server.
      Another issue with Ajax is that it can be used maliciously without the user discovering it. Since Ajax is designed to run without user interaction it can easily be run on a webpage hijacking session information and sending it to an attacker.

SUMMARY/CONCLUSIONS

        Ajax provides functionality to create a robust web application. If an Ajax web application is coded properly it will run faster than and as secure as a non-Ajax program. Ajax also allows websites to reduce their overall bandwidth usage and server load by reducing the amount of full page loads.
      One major advantage of Ajax is that it very easy to learn if you understand html. Since Ajax is a mixture of technologies a developer will learn how to write web pages and server scripts all while learning Ajax. The example shown in this paper could be written by an experienced Ajax developer in under ten minutes. As Ajax is becoming more popular many toolkits have been produced that allow developers to utilize Ajax functionality without having to code the actual requests. These toolkits are extremely useful when coding large projects because they provide a standard that is well defined and easy to use.
            AJAX is one of the most valuable tools in a web developer’s toolbox.  With AJAX, a developer is able to move away from the traditional submit/refresh cycle that traditional web forms tend to lock design into.  AJAX allows functionality similar to that which used to have to be provided by browser plug-ins.  It is reliable to develop in because it is compatible and nearly everyone using the web can use AJAX.  Finally, it is poised to be an important part of web development for a long time.  AJAX is the most compatible web application solution available today.  For intranet applications, something like XAML or XUL may be a better idea, but for standard internet applications, the only reasonable choices currently are AJAX and Flash.

1 comment:

leave your opinion