1.4. Technologies of AJAX

Almost a decade ago, the Microsoft Exchange Server team created an ActiveX control called XMLHttpRequest that could be instantiated from JavaScript and used to communicate with the server. Using the XMLHttpRequest object, you could send information to the server and get data back without clearing the screen and painting a completely new HTML page. JavaScript code could then manipulate the HTML dynamically on the client, avoiding the annoying flash and the wait that users associate with Web browsing. This functionality was not limited to Internet Explorer for long. Soon, other browsers included XMLHttpRequest objects as well. Developers could now write richer applications with their reach extending across various operating systems.

Figure 1-2. Figure 1-2

The browsers that can make use of this object include the following:

  • Internet Explorer 5.0 and above (currently in version 8.0)

  • Safari 3.1

  • Firefox 3

  • Opera 8+

  • Netscape 9

The browsers also created an advanced Document Object Model (DOM) to represent the browser, the window, the page, and the HTML elements it contained. The DOM exposed events and responded to input, allowing the page to be manipulated with script. Dynamic HTML (DHTML) opened the door to writing rich interfaces hosted within the Web browser. Developers started writing hundreds and even thousands of lines of JavaScript code to make rich and compelling applications that would not require any client installation and could be accessed from any browser anywhere. Web applications began to move to a whole new level of richness. Without AJAX libraries, you would be faced with writing lots and lots of JavaScript code and debugging the sometimes subtle variations in different browsers to reach this new level of richness.

1.4.1. JavaScript Libraries and AJAX

Developers have had access to AJAX technologies for years, and many have been leveraging AJAX to push the limits of what can be done in the Web browser. But what is really making AJAX more compelling now are the comprehensive script libraries and integration with server technologies that make it easier to write rich Web applications and avoid the need to become an expert on the different versions of JavaScript. A JavaScript library is referenced within the HTML of a page by using the <script> tag:

<html>
    <head>
        <script src="http://www.someSite.com/someScript.js"
          type="text/javascript">
        </script>
    </head>
...

The script is downloaded and cached by the browser. Other pages within the application can reference the same URL for script, and the browser will not even bother to go back to the server to get it. The functionality of that script file is available for use from within the page rendered to the browser. A script library sent to the browser and then leveraged for writing a richer UI and a more responsive application is at the heart of all AJAX libraries.

1.4.2. The Initiator Component

To initiate calls to the back end server, you need JavaScript on the client to invoke the XMLHttpRequest object, which takes charge of making these out-of-bound calls. This component works to send data back and forth asynchronously. This core capability is browser-independent and allows for requests and responses to occur without interrupting the end user experience.

1.4.3. The JavaScript Component

AJAX technologies take advantage of the common support for JavaScript found in modern browsers. Because there is a standard that is supported across the various browsers, you can write scripts knowing that they will run. This wasn't always the case.

In the mid-1990s, Netscape and Microsoft (along with others) collaborated on a standard for a scripting language that they would support in their Web browsers. The standard is called EcmaScript. Microsoft's implementation is called JScript, but the language is generally referred to as JavaScript, as it was called in Netscape. (It has nothing to do with Java, but someone must have thought the association was useful for marketing purposes.) JavaScript program snippets are sent down to the browser along with the HTML, and they run inside the user's browser to affect how the page is processed on the client.

JavaScript is not compiled; it is interpreted. There is no static type-checking as you get in C++ and C#. You can declare a variable without needing to specify a type, and the type to which the variable refers can change at any time. This makes it easy to start programming in JavaScript, but there is inevitably a certain amount of danger in allowing the data type of a variable to change dynamically at runtime. In the following snippet, notice that the variable can reference any type without difficulty:

var something = 1;
something = true;
something = "a string";

JavaScript is a dynamic language. Types can actually be extended during program execution by other code. This means that you can write code that creates types on the fly. Because there is no enforcement of type safety, your code can receive these types as parameters or return values without any problem. This provides a great degree of flexibility and coding power.

The fundamental types in JavaScript are strings, numbers, Booleans, and functions. There is also support for objects and arrays, which are collections of the fundamental types. Some additional objects that are considered essential for many programming tasks are included in JavaScript. This includes support for regular expressions and date and time operations.

You can use the plus operator on strings in JavaScript to concatenate them:

var theEnd = "THE END.";
var result = "Beginning, " + "middle, and " + theEnd;

In this example, the result variable is now the string: "Beginning, middle, and THE END".

JavaScript interpreters use the IEEE floating-point standard for storing numbers. Ignoring the gory details, you can assume that for most programming tasks you won't have any trouble.

The Boolean type in JavaScript is about what you would expect it to be but maybe not exactly so. The Boolean represents whether or not an expression is true, but it uses the C-style convention using integer values 0 and 1.

Variables can exist in JavaScript without having a value, and a variable may simply be undefined, which can produce unexpected results. In this snippet of JavaScript, three variables are declared, and all of these comparisons are designed to return a true value.

<script type="text/javascript">
      var one = 1;
      var zero = 0;
      var undefinedVar;

      if(one) {
         alert("1 is true");
      }

      if(!zero) {
         alert("0 is false");
      }

      if(!undefinedVar) {

         // this test tells us that "undefinedVar" either contains 0,
         // or is really undefined: both of which equate to false
         alert("undefinedVar is false");
      }

      if(one != zero) {
         alert("one and zero are not the same");
      }
</script>

You can check specifically to see if a variable has been defined like this:

if( typeof(undefinedVar ) == "undefined" ) {
   alert("undefinedVar is undefined");
}

Variables can also have a null value, which is not the same thing as being undefined, because a null value does constitute a value.

Functions are also real types in JavaScript. They can accept arguments and return values. Functions can be passed to other functions and can be created dynamically by other script code.

Here are two equivalent definitions for a function called Add() that will take two variables and return the result of applying the plus operator. Notice that this did not state that it takes two numbers. Remember, JavaScript variables do not have a defined type, so I could just as easily pass two strings and concatenate them with my Add() function.

<script type="text/javascript">
      function Add(x, y) {
         return x + y;
      }

      var AddAgain = function(x, y) { return x + y; }
</script>

Once either of these styles is used to create a function, it can be called from that scope and any nested scope to perform the addition. There is no advantage to one of these forms over the other. You can simply choose to use the syntax that you prefer.

<script type="text/javascript">
      var result = Add(36, 24);
      alert(result);  //displays 60

      var stringResult = Add("Hello ", "there.");
      alert(stringResult); //displays "Hello there."
</script>

Objects and arrays are just collections of other types. Array types do not require that the values they hold be named. Instead, you can access them by index. The values held in an object are referenced by field or property names. Objects can also hold functions (which can be accessor functions to give public visibility to local variables), which lets you create data structures that represent entities in JavaScript code. Missing from this sort of object-oriented programming is a concept of type inheritance. Although, there are things like the Microsoft AJAX Library, which provides a set of classes and recommended patterns for achieving inheritance in JavaScript, making it more natural to switch between JavaScript and other high-level languages. The following code example includes a definition for an Album object that holds and returns the artist and album title. An array is then used to store information about several albums.

<script type="text/javascript">
      // define an object named Album – note that this object is typeless
      Album = function(title, artist) {
         var _title = title;
         var _artist = artist;

this.get_title = function() { return _title; }
         this.get_artist = function() { return _artist; }
      }

      // create object instances by calling the constructor
      var albumA = new Album("Rift", "Phish");
      var albumB = new Album("A Picture of Nectar", "Phish");

      // create an array to hold the instances (also typeless)
      var albumArray = new Array();

      albumArray[0] = albumA;
      albumArray[1] = albumB;

      // iterate over the array to show the album titles
      for(var i = 0; i < albumArray.length; i++) {
         alert((albumArray[i]).get_title()); // call get_title accessor
      }
</script>

1.4.4. The Web Services Component

The fundamental concept of Web services is powerful and continues to evolve and advance. The original Simple Object Access Protocol (SOAP) standard is the use of the HTTP protocol to pass XML-formatted data to the server from a client and receive XML-formatted results in return. This can be from within a Web browser using the XMLHttpRequest object or directly from a desktop application or another server. Before Web services became widely adopted, it was not uncommon for developers to programmatically request a page as an HTML document and extract the desired data from it, a technique known as screen-scraping. This causes all sorts of frustrations as sites are continually updated and the screen-scraping clients must try to keep up by modifying their parsing code to adapt to the new HTML that the target site is rendering.

This resulted in frustration, because sites that presented data using HTML visual pages were prone to modifying those pages, and this would break the screen-scraping program, which expected to see the data in the original format. Web services were created as a nonvisual way to transfer data over the Web, and they are the natural way to isolate remote method calls from the presentation layer. Now, instead of screen-scraping, you are able to call a Web service and have XML-formatted data returned that is easily consumed by a program.

By passing plain-text data formatted as XML and by eliminating the visual elements, data passed in Web services is much easier to parse than HTML. Moreover, since XML can contain an embedded schema, code can inspect the schema and use it to determine the structure and types used in the data. You can extend the schema passed with the data being returned without worrying that consuming applications will be broken, and therefore XML readers can be somewhat tolerant of modifications that would have certainly caused a screen-scraper a great deal of grief!

The schema for data can be extended without requiring all consumers to be updated. Consumers can easily get the parts of the XML document they wish to process and disregard the rest. This has progressed beyond simple XML formats. Unlike previous implementations of Web services, you can now define Web service contracts to be built to employ arbitrary encoding and utilize any one of a number of wire protocols. What drives the Web service concept is the ability to access data easily from various applications in a loosely coupled way, and the new Microsoft Windows Communication Foundation (WCF) takes this concept to a completely new level, allowing the contract to specify wire protocols, deployment strategies, and logging infrastructure, along with providing support for transactions.

ASP.NET AJAX provides a set of JavaScript proxy objects to access some new Web services built into ASP.NET. Profile information, membership services, and role management can be easily accessed from the client. Developers don't need to create their own infrastructure to support these fundamental application services but can include a few lines of code to take advantage of server resources from JavaScript code running in the browser, thereby dramatically extending the reach of ASP.NET to include both the client and the server. Moreover, because the JavaScript libraries are designed to be easy to use by developers already familiar with server-side .NET programming, all of this extra functionality comes in a friendly package that is easy to leverage.

1.4.5. The Dynamic HTML Component

Dynamic HTML is not a freestanding technology. It is the use of a set of technologies in a specific way. HTML is returned to the browser following a Web server request. The browser then renders the page, and the user is able to view it. The browser also exposes the DOM that represents the structure of the HTML being displayed. The DOM can be accessed from JavaScript embedded in, or referenced by, the page. The appearance of the HTML is affected by applying Cascading Style Sheets (CSS), which control colors, fonts, position, visibility, and more. You can bind JavaScript code to events that the browser will raise when users perform certain actions, such as hovering over a particular element or entering text in a textbox. The JavaScript code can update text or manipulate the CSS settings for elements within the page. It can also communicate with the server to expand the dynamic nature of the page even further. The user will see a dynamically changing user interface that responds to his actions in real time, which will greatly enhance his overall experience, thereby increasing his productivity and satisfaction with the application. This one piece of the pie is the one that changes the underlying page without the page refresh.

All these pieces together, in the end, provide you the tools that you need to build state-of-the-art applications for today's Web world.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset