Pages

Saturday, January 31, 2009

Basics of DOM

The great divide between programmers (who work with back-end applications) and Web programmers (who spend their time writing HTML, CSS, and JavaScript) is long standing. However, the Document Object Model (DOM) bridges the gap and makes working with both XML on the back end and HTML on the front end possible and an effective tool. In this article, we check the Document Object Model, explains its use in Web pages and starts to explore its usage from JavaScript.

Like many Web programmers, you may have probably worked with HTML. HTML is how programmers start to work on a Web page; HTML is often the last thing they do as they finish up an application or site, and tweak that last bit of placement, color or style. And, just as common as using HTML is the mis understanding about what exactly happens to that HTML once it goes to a browser to render to the screen. Before we go deep into what you might think happens; and why it is probably wrong, one need to be clear on the process involved in designing and serving Web pages:
  1. Some one creates HTML in a text editor or IDE.

  2. Then HTML is uploaded to a web server, like Apache HTTPD, and make it public on the Internet or an intranet.

  3. A user requests your Web page with a browser like Firefox or Safari.

  4. The user's browser makes a request for the HTML to your Web server.

  5. The browser renders the page it receives from the server graphically and textually; users look at and activate the Web page.

While this feels very basic, things will get interesting quickly. In fact, the tremendous amount of "stuff" that happens between steps 4 and 5 is what the focus of this article. The term "stuff" really applies too, since most programmers never really consider exactly what happens to their markup when a user's browser is asked to display it:
  • Does the browser just read the text in the HTML and display it?

  • What about CSS, especially if the CSS is in an external file?

  • And what about JavaScript; again often in an external file?

  • How does the browser handle these items and how does it map event handlers, functions, and styles to that textual markup?

It turns out that the answer to all these questions is the Document Object Model. So, without further ado, let's dig into the DOM.

Web programmers and markup

For most programmers, their job ends where the Web browser begins. In other words, once you drop a file of HTML into a directory on your Web server, we usually file it away as "done" and (hopefully) never really think about it again! That's a great goal when it comes to writing clean, well-organized pages, too; there's nothing wrong with wanting your markup to display what it should, across browsers, with various versions of CSS and JavaScript.

The problem is that this approach limits a programmers' understanding of what really happens in the browser. More importantly, it limits your ability to update, change, and restructure a Web page dynamically using client-side JavaScript. Get rid of that limitation, and allow even greater interaction and creativity on your Web sites.

What the programmer does

As a typical Web programmer, we probably fire up your text editor and IDE and start to enter HTML, CSS, or even JavaScript. It's easy to think about those tags and selectors and attributes only as little tasks that we do to make a site look just right. But we need to stretch our mind beyond that point; instead, realize that we are organizing your content. Don't worry; promise this won't turn into a lecture on the beauty of markup, how we must realize the true potential of our Web page, or anything else meta-physical. What we do need to understand is exactly what our role in Web development is.

When it comes to how a page looks, at best we're only able to make suggestions. When we provide a CSS stylesheet, a user can override your style choices. When we provide a font size, a user's browser can alter those sizes for the visually impaired or scale them down on massive monitors (with equally massive resolutions). Even the colors and font faces you choose are subject to the monitor of users and the fonts that users install on their systems. While it's great to do your best in styling a page, that's not the largest impact you have on a Web page.

What you do absolutely control is the structure of your Web page. Our markup is unchangeable and unalterable and users can't mess with it; their browsers can only retrieve it from your Web server and display it. But the organization of that page; whether this word is inside that paragraph or in the other div is solely up to you. When it comes to actually changing our page (which is what most Ajax applications focus on), it's the structure of your page that you operate on. While it's nice to change the color of a piece of text, it's much more dramatic to add text or an entire section to an existing page. No matter how the user styles that section, we work with the organization of the page itself.

What the markup does

Once we realize that our markup is really about organization, we can view it differently. Rather than think that an h1 causes text to be big, black, and bold, think about an h1 as a heading. How the user sees that; and whether they use your CSS, their own, or some combination of the two this is a secondary consideration. Instead, realize that markup is all about providing this level of organization; a p indicates that text is in a paragraph, img denotes an image, div divides a page up into sections, and so forth.

We should also be clear that style and behavior (event handlers and JavaScript) are applied to this organization after the fact. The markup has to be in place to be operated upon or styled. So, just as we might have CSS in an external file to your HTML, the organization of our markup is separate from its style, formatting, and behavior. While we can certainly change the style of an element or piece of text from JavaScript, it's more interesting to actually change the organization that your markup lays out.
As long as we keep in mind that our markup only provides an organization, or framework, for our page, we're ahead of the game. And a little further on, we'll see how the browser takes all this textual organization and turns it into something much more interesting; a set of objects, each of which can be changed, added to, or deleted.

The advantages of text markup

Before we discuss the Web browser, it's worth considering why plain text is absolutely the best choice for storing your HTML. Without getting into the ups and downs, simply recall that our HTML is sent across a network to a Web browser every time the page is viewed (putting caching and so forth aside for simplicity's sake). There's simply no more efficient approach to take than passing along text. Binary objects, graphical representations of the page, a re-organized chunk of markup... all of these are harder to send across the network than plain text files.

Add to that the value that a browser adds to the equation. Today's browsers allow users to change the size of text, scale images, download the CSS or JavaScript for a page (in most cases), and a lot more -- this all precludes sending any kind of graphical representation of the page to the browser. Instead, the browser needs the raw HTML; it can apply whatever processing to the page in the browser rather than trusting the server to handle that task. In the same way, separating CSS from JavaScript and separating those from the HTML markup requires a format that is easy to separate. Text files again are a great way to do just this.

Last, but not least, remember that the promise of new standards like HTML 4.01 and XHTML 1.0 and 1.1 separates content (the data in our page) from presentation and style (usually applied by CSS). For programmers to separate their HTML from their CSS, then force a browser to retrieve some representation of a page that melds these all back together, defeats much of the advantage of these standards. To keep these disparate parts separate all the way down to the browser allows the browser the most flexibility in getting the HTML from the server.

A closer look at Web browsers

For some of us, everything we've read so far may be droll review of your role in the Web development process. But when it comes to what the Web browser does, many of the most Web designers and developers often don't realize what actually goes on "under the hood." we'll have a focus on that in this section. And don't worry, code is coming soon, but hold off on your coding intention because really understanding exactly what a Web browser does is essential to our to code work correctly.

The disadvantages of text markup

Just as text markup has terrific advantages for a designer or page creator, it also has rather significant disadvantages for a browser. Specifically, browsers have a very difficult time directly representing text markup to a user visually. Consider these frequent browser tasks:
  • Apply CSS styles; often from multiple stylesheets in external files, to markup based on the type of element, its class, its ID, and its position in the HTML document.

  • Apply styles and formatting based on JavaScript code; also often in external files to different parts of the HTML document.

  • Change the value of form fields based on JavaScript code.

  • Support visual effects like image rollovers and image swapping based on JavaScript code.

The complexity isn't in coding these tasks; it's fairly easy to do each of these things. The complexity comes from the browser actually carrying out the requested action. If markup is stored as text and, for example, you want to center the text ( text-align: center ) in a p element in the center-text class, how we do accomplish that?
  • Do you add inline styling to the text?

  • Do you apply the styling to the HTML text in the browser and just keep up with which content to centered or not center?

  • Do you apply unstyled HTML and then apply format after the fact?

These very difficult questions are why few people code browsers these days.

Clearly, plain text isn't a great way to store HTML for the browser even though text was a good solution for getting a page's markup in the first place. Add to this the ability for JavaScript to change the structure of a page and things really get tricky. Should the browser rewrite the modified structure to disk? How can it keep up with what the current stage of the document is?

Clearly, text isn't the answer. It's difficult to modify, clumsy to apply styles and behavior to, and ultimately bears little likeness to the dynamic nature of today's Web pages.

Moving to a tree view

The answer to this problem -- at least, the answer chosen by today's Web browsers -- is to use a tree structure to represent HTML. Take a look at Listing below, a rather simple and boring HTML page represented as text markup.

Simple HTML Page in text markup
<html>
<head>
<title>Trees, trees, everywhere</title>
</head>
<body>
<h1>Trees, trees, everywhere</h1>
<p>Welcome to a
<em>really</em>
boring page.
</p>
<div>
Come again soon.
<img src="come-again.gif" />
</div>
</body>
</html>


The browser takes this and converts it into a tree-like structure

We made a few very minor simplifications to keep this article on track. Experts in the DOM or XML will realize that whitespace can have an effect on how text in a document is represented and broken up in the Web browser's tree structure. Getting to this does little but confuse the matter, so if we know about the effect of whitespace, great; if not, read on and don't worry about it. When it becomes an issue, we'll find out all we need at that time.

Other than the actual tree background, the first thing we might notice here is that everything in the tree begins with the outer-most, containing element of HTML, which is the html element. This is called the root element in keeping with the tree metaphor. So even though this is at the bottom of the tree, always begin here when you look at and analyze trees. If it helps, we're welcome to flip the whole thing upside down, although that does stretch the tree metaphor a bit.

From the root flow out lines that show the relationships between different pieces of markup. The head and body elements are children of the html root element; title is a child of head and then the text "Trees, trees, everywhere" is a child of title. The entire tree is organized like this until the browser gets a structure.

A few additional terms

To carry on with the tree metaphor, head and body are said to be branches of html . They are branches because they in turn have children of their own. When we reach the extremities of the tree, we'll run into mostly text such as "Trees, trees, everywhere" and "really." These are often referred to leaves because they have no children of their own. We don't need to memorize all these terms and it is often easier to just visualize the tree structure when you try to figure out what a particular term means.

The value of objects

Now that we've some basic terminology in hand, and iit's time to focus more on those little rectangles with element names and text inside. Each rectangles is an object; that's where the browser resolves some of these problems with text. By using objects to represent each piece of the HTML document, it becomes very easy to change the organization, apply styles, allow JavaScript to access the document, and much more.

Object types and properties

Each possible type of markup gets its own object type. For instance, elements in your HTML are represented by an Element object type. The text in our document is represented by a Text type, attributes are represented by Attribute types, and right on down the line.

So the Web browser not only gets to use an object model to represent our document; getting away from having to deal with static text -- but can immediately tell what something is by its object type. The HTML document is parsed and turned into the set of objects and then things like angle brackets and escape sequences (for example, using < for < and > for > ) no longer become an issue. This makes the job of the browser, at least after it parses the input HTML, much easier. The operation to figure out whether something is an element or an attribute and then determine what to do with that type of object is simple.

By using objects, the Web browser can then change those objects' properties. For example, each element object has a parent and a list of children. So adding a new child element or text is simply a matter of adding a new child to an element's list of children. These objects also have a style property, so it becomes trivial to change the style of an element or piece of text on the fly. For example, we might change the height of a div using JavaScript like this:

someDiv.style.height = "300px"
In other words, the Web browser can very easily change the appearance and structure of the tree using object properties like this. Compare this to the complicated sorts of things that the browser must do if it represented the page as text internally; every change of property or structure requires the browser to rewrite the static file, re-parse it, and re-display it on the screen. All of this becomes possible with objects.

At this point, take time to pull open some of the HTML documents and sketch them out as trees. While that seems an unusual request; especially from an article that contains very little code; we need to become familiar with the structure of these trees if we want to be able to manipulate them.

In the process, we'll probably find some oddities. For example, consider the following situations:
  • What happens to attributes?

  • What about text that is broken up with elements, like em and b ?

  • And what about HTML that isn't structured correctly (like when a closing p tag is missing)?

Once familiar with these sorts of issues, we can understand these coming sections lot better.

Strict is sometimes good

If you have tried the exercise above just mentioned, you probably found some of the potential troubles for a tree-view of your markup (if you didn't exercise, just take my word for it!). In fact, we'll find several of these in listing above and figure starting with the way the p element was broken up. If it is asked with a typical Web developer; What the text content of the p element is, the most common answer would be, "Welcome to a really boring Web page." If we compare this with Figure above, we'll see that this answer; although logical, isn't at all correct.

It turns out that the p element has three different child objects and none contain all of the text "Welcome to a really boring Web page." You'll find parts of that text, like "Welcome to a "and " boring Web page", but not all of it. To understand this, remember that everything in your markup has to be turned into an object of some type.

Furthermore, the order does matter! Can we imagine how users would respond to a Web browser if it showed the correct markup, but in a different ordering than you provided in your HTML? Paragraphs were implemented in between titles and headings, even when that's not how we organized the document ourself? Obviously, the browser must preserve the order of elements and text.

In this case, the p element has three distinct parts:
  • The text that comes before the em element

  • Tthe em element itself

  • The text that comes after the em element

If we mix this ordering up, we might apply the emphasis to the wrong portion of text. To keep this all straight, the p element has three object children in the order that those things appeared in the HTML in listing above. Further, the emphasized text "really" isn't a child element of p ; it is a child of em which is a child of p .

It is very important for we to understand this concept. Even though the "really" text will probably display along with the rest of the p element's text, it still is a direct child of the em element. It can have different formatting from the rest of the p and can be moved around independently of the rest of the text.

To help cement this in your mind, try to diagram the HTML in Listings below, making sure you keep text with its correct parent (despite how that text might end up looking on screen).

Listing.. Markup with slightly tricky element nesting
<html>
<head>
<title>This is a little tricky</title>
</head>
<body>
<h1>Pay <u>close</u> attention, OK?</h1>
<div>
<p>This p really isn't <em>necessary</em>, but it makes the
<span id="bold-text">structure <i>and</i> the organization</span>
of the page easier to keep up with.</p>
</div>
</body>
</html>
Listing.. Even better nesting of elements
<html>
<head>
<title>Trickier nesting, still</title>
</head>
<body>
<div id="main-body">
<div id="contents">
<table>
<tr><th>Steps</th><th>Process</th></tr>
<tr><td>1</td><td>Figure out the <em>root element</em>.</td></tr>
<tr><td>2</td><td>Deal with the <span id="code">head</span> first,
as it's usually easy.</td></tr>
<tr><td>3</td><td>Work through the <span id="code">body</span>.
Just <em>take your time</em>.</td></tr>
</table>
</div>
<div id="closing">
This link is <em>not</em> active, but if it were, the answers
to this <a href="answers.html"><img src="exercise.gif" /></a> would
be there. But <em>do the exercise anyway!</em>
</div>
</div>
</body>
</html>

What about attributes?

Did we run across any problems as you tried to figure out what to do with attributes? As I mentioned, attributes do have their own object type, but an attribute is really not the child of the element it appears on -- nested elements and text are not at the same "level" of an attribute and you'll notice that the answers to the exercises in two Listings above; do not have attributes shown.

Attributes are in fact stored in the object model that a browser uses, but they are a bit of a special case. Each element has a list of attributes available to it, separate from the list of child objects. So a div element might have a list that contained an attribute named "id" and another named "class."

Keep in mind that attributes for an element must have unique names; in other words, an element cannot have two "id" or two "class" attributes. This makes the list very easy to keep up with and to access. As you'll see in the next article, you can simply call a method like getAttribute("id") to get the value of an attribute by its name. You can also add attributes and set (or reset) the value of existing attributes with similar method calls.

It's also worth pointing out that the uniqueness of attribute names makes this list different than the list of child objects. A p element could have multiple em elements within it, so the list of child objects can contain duplicate items. While the list of children and the list of attributes operate similarly, one can contain duplicates (the children of an object) and one cannot (the attributes of an element object). Finally, only elements can have attributes; so text objects have no lists attached to them for storing attributes.

Sloppy HTML

Before we move on, one more topic is worth some time when it comes to how the browser converts markup to a tree representation; how a browser deals with markup that is not well-formed. Well-formed is actually a term largely used in XML and means two basic things:
  • Every opening tag has a matching closing tag. So every <p> is matched in the document by a </p>, every <div> by a </div>, and so forth.

  • The innermost opening tag is matched with the innermost closing tag, then the next innermost opening tag by the next innermost closing tag, and so forth. So <b><i>bold and italics</b></i> would be illegal because the innermost opening tag <i> -- is improperly matched with the innermost closing tag -- <b>. To make this well-formed, you would need to switch either the opening tag order or the closing tag order. (If you switched both, you'd still have a problem).

Study these two rules closely. They are both rules that not only increase the simple organization of a document, but they also remove ambiguity. Should bolding be applied first and then italics? Or the other way around? If it seems that this ordering and ambiguity is not a big deal, remember that CSS allows rules to override other rules so if, for example, the font for text within b elements was different than the font for within i elements, the order in which formatting was applied becomes very important. Therefore, the well-formedness of an HTML page comes into play.

In cases where a browser receives a document that is not well-formed, it simply does the best it can. The resulting tree structure is at best an approximation of what the original page author intended and at worst something completely different. If you ever loaded your page in a browser and saw something completely unexpected, you might have viewed the result of a browser trying to guess what your structure should be and doing the job poorly. Of course, the fix to this is pretty simple: Make sure your documents are well-formed!

Introducing the DOM

So far you've heard that browsers turn a Web page into an object representation and maybe you've even guessed that the object representation is a DOM tree. DOM stands for Document Object Model and is a specification available from the World Wide Web Consortium (W3C) (one can check out several DOM-related links in the Resources).

More importantly though, the DOM defines the objects' types and properties that allow a browser to represent markup. (The next article in this series focuses on the specifics of using the DOM from your JavaScript and Ajax code.)

The document object

First and foremost; you will need to access the object model itself. This is remarkably easy; to use the built-in document variable in any piece of JavaScript code running on your Web page, you can write code like this:
var domTree = document; 
Of course, this code is pretty useless in and of itself, but it does demonstrates that every Web browser makes the document object available to JavaScript code and that the object represents the complete tree of markup.

Everything is a node

Clearly, the document object is important, but is just the beginning. Before we can move further, we need to learn another term: node. You already know that each bit of markup is represented by an object, but it's more than just any object -- it's a specific type of object, a DOM node. The more specific types; like text, elements, and attributes -- extend from this basic node type. So we have text nodes, element nodes, and attribute nodes.

If one have programmed much in JavaScript, it should occur to you that you might already be using DOM code. If you followed this Ajax series thus far, then you've definitely used DOM code for some time now. For example, consider the line var number = document.getElementById("phone").value; uses the DOM to find a specific element and then to retrieve the value of that element (in this case, a form field). So even if you didn't realize it, we have used the DOM every time you typed document into your JavaScript code.

To refine the terms we've learnt then, a DOM tree is a tree of objects, but more specifically it is a tree of node objects. In Ajax applications, or any other JavaScript; we can work with those nodes to create such effects as removing an element and its content, highlighting a certain piece of text, or adding a new image element. Since this all occurs on the client side (code that runs in your Web browser), these effects take place immediately without communication with the server. The end result is often an application that feels more responsive because things on the Web page change without long pauses while a request goes to a server and a response is interpreted.

In most programming languages, we need to learn the actual object names for each type of node, learn the properties available, and figure out about types and casting; but none of this is necessary in JavaScript. WE can simply create a variable and assign it the object you want (as you've already seen):

var domTree = document;
var phoneNumberElement = document.getElementById("phone");
var phoneNumber = phoneNumberElement.value;
There are no types and JavaScript handles creating the variables and assigning them the correct types as needed. As a result, it becomes fairly trivial to use the DOM from JavaScript (a later article focuses on the DOM in relation to XML and things are a little trickier).

Sunday, January 25, 2009


First, take this last bit of overview before see into code.

Make sure to clear on this idea of the Web 2.0. When anybody hears the term Web 2.0, one asks; "What's Web 1.0?" Although web 1.0 is rarely heard, it is meant to refer to the traditional Web where we have a very distinct request and response model. For example, go to Amazon.com and click a button or enter a search term. A request is made to a server and then a response comes back to your browser. That request has a lot more than just a list of books and titles, though; it's actually another complete HTML page. As a result, you probably get some flashing or flickering as your Web browser's screen is redrawn with this new HTML page. In fact, you can clearly see the request and response, done by each new page you see.

The Web 2.0 dispenses with this very visible back-and-forth (to a large degree). As an example, visit a site like Gmail or newer Yahoo (links to both of these Web 2.0, Ajax-powered sites are in Resources). On Google Maps, for example, one can drag the map around and zoom in and zoom out with very little redrawing. Of course, requests and responses do go on here, but all behind the scenes. As a user, the experience is much more pleasant and feels a lot like a desktop application. This new feel and paradigm that is observed when someone refers to Web 2.0.

What care should care? how to make these new interactions possible? Obviously, we've still got to make requests and field responses, but it's the redrawing of the HTML for every request/response interaction that gives the perception of a slow, clunky Web interface. So clearly you need an approach that allows you to make requests and receive responses that include only the data you need, rather than an entire HTML page as well. The only time you want to get a whole new HTML page is when ... well ... when you want the user to see a new page.

But most interactions add details or change body text or overlay data on the existing pages. In all of these cases, Ajax and a Web 2.0 approach make it possible to send and receive data without updating an entire HTML page. And to any frequent Web surfer, this ability will makes application feel faster, more responsive, and bring them back over and over again.


Introducing XMLHttpRequest


To make all this flash and wonder actually happen, need to become clear and familiar with a JavaScript object called XMLHttpRequest. This little object; which has actually been around in several browsers for quite a while. This is key to Web 2.0; Ajax, and pretty much everything else you learn about in this column for the next several months. To give a really quick overview, here are just a few of the methods and properties frequently used on this object:

  1. open(): Sets up a new request to a server.

  2. send(): Sends a request to a server.

  3. abort(): Terminates the current request.

  4. readyState: Provides the current HTML ready state.

  5. responseText: The text that the server sends back to respond to a request.


Don't worry about understanding all these; each of these methods and properties will be discussed in detail in future. What should be done with this stuff; though, its a good idea of what to do with XMLHttpRequest. Notice that each of these methods and properties relate to sending a request and dealing with a response. In fact, if you saw every method and property of XMLHttpRequest, they would all relate to that very simple request/response model.

So clearly, one won't learn about an amazing new GUI object or some sort of approach to create user interaction; we will work with simple requests and simple responses. It may not sound exciting; but careful usage of this object could change an application interaction method.

The simplicity of new


First, we need to create a new variable and assign it to an instance of the XMLHttpRequest object. That's pretty simple in JavaScript; we just use the new keyword with the object name, like you see in Listing below.

Listing.. Create a new XMLHttpRequest object


<script language="javascript" type="text/javascript">

var request = new XMLHttpRequest();

</script>


So we have created a variable in JavaScript with var, give it a name (like "request"), and then assign it to a new instance of XMLHttpRequest.

At that point, it is ready to be used with above functions.

Error handling


With out error handling in life, several problems could occour. A slightly better approach is to create this object and have it fail if something goes wrong. For example, many older browsers (believe it or not, people are still using old versions of Netscape Navigator) don't support XMLHttpRequest and one need to let those users know that something has gone wrong. Listing below shows how you may create this object so if something fails, it throws out a JavaScript Message (alert).
Listing.. Create XMLHttpRequest with some error-handling abilities



<script language="javascript" type="text/javascript">

var request = false;

try {

request = new XMLHttpRequest();

} catch (failed) {

request = false;

}


if (!request)

alert("Error initializing XMLHttpRequest!");

</script>

Make sure to understand each of these steps:

  1. Create a new variable called request and assign it a false value. we'll use false as a condition that means the XMLHttpRequest object hasn't been created yet.

  2. In a try/catch block;

    • Try and create the XMLHttpRequest object.

    • If that fails catch(failed) block, ensure that request is still set to false.


  3. Check and see if request is still false (if things are going okay, it won't be).

  4. If there was a problem (and request is false), use a JavaScript alert to tell users there was a problem.


This is pretty simple; it takes longer to read and write about than it does to actually understand for most JavaScript and Web developers. Now we've got an error-proof piece of code that creates an XMLHttpRequest object and even intimates if something goes wrong.

Dealing with Microsoft Browsers


If same above code is run on Microsoft browser(Internet Explorer), message will be displayed saying "Error initializing XMLHttpRequest!".
Clearly, something isn't working; Internet Explorer is hardly an out-of-date browser and about 70 percent of the world uses Internet Explorer one needs a different approach to deal with Microsoft's browsers.

It turns out that Microsoft supports Ajax, but calls its version of XMLHttpRequest something different.

In fact, it calls it several different things.

For a newer version of Internet Explorer,
Msxml2.XMLHTTP object needs to be used.

Some older versions of Internet Explorer use Microsoft.XMLHTTP; both these objects needs to be supported.


Listing.. Adding support for Microsoft browsers

<script language="javascript" type="text/javascript">

var request = false;

try {

request = new XMLHttpRequest(); //Non Microsoft Browsers. Firefox, Opera, Chrome

} catch (trymicrosoft) {

try {

request = new ActiveXObject("Msxml2.XMLHTTP"); //New Microsoft Browsers

} catch (othermicrosoft) {

try {

request = new ActiveXObject("Microsoft.XMLHTTP");//Old Microsoft Browsers

} catch (failed) {

request = false;

}

}

}

if (!request)

alert("Error initializing XMLHttpRequest!");

</script>

In above code all the required possibilities are checked well. So that if any error occours with creation of XMLHTTP Request, a message will be displayed.

Dynamic Java Script


Take a look back at Listings above and notice that all of this code is nested directly within script tags.

When JavaScript is coded like that and not put within a method or function body, it's called static JavaScript.

This means that the code is run sometime before the page is displayed to the user.

It's not 100 percent clear from the specification precisely when this code runs and browsers do things differently; still, you're guaranteed that the code is run before users can interact with your page. That's usually XMLHttpRequest obejct is now created by Ajax programmers.

With code setup like this, you'll need to call this method before you do any Ajax work. So you might have something like Listing below


Listing.. Use an XMLHttpRequest creation method

<script language="javascript" type="text/javascript">

var request;

/*Function to create XMLHttpRequest Object */

function createRequest() {

try {

request = new XMLHttpRequest();

} catch (trymicrosoft) {

try {

request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (othermicrosoft) {

try {

request = new ActiveXObject("Microsoft.XMLHTTP");

} catch (failed) {

request = false;

}

}

}

if (!request)

alert("Error initializing XMLHttpRequest!");

}

/*Calling Function*/

function getInfo() {

createRequest();

// Do something with the request variable

}

</script>


The only concern with this code; and the reason most Ajax programmers don't use this approach
is that it delays error notification. Suppose if we have a complex form with 10 or 15 fields, selection boxes, and the like, and some Ajax code is fired when the user enters text in field
14 (way down the form). At that point, getInfo() runs, tries to create an XMLHttpRequest object, and (for this example) fails.
Then an alert is displayed out to the user, telling them (in so many words) that they can't use this application. But the user has already spent time entering data in the form!
That's pretty annoying and annoyance; is not something that typically entices users back to your site.

In the case where static JavaScript is used, the user is going to get an error as soon as they hit your page. Is that also annoying? Perhaps; it could make users mad that your Web application won't run on their browser. However, it's certainly better than displaying out that same error after they've spent 10 minutes entering information. For that reason alone, I encourage to set up code statically and let users know early on about possible problems.

Sending requests with XMLHttpRequest


Once we have our request object, we can begin the request/response cycle. Remember, XMLHttpRequest's only purpose is to allow you to make requests and receive responses. Everything else -- changing the user interface, swapping out images, even interpreting the data that the server sends back -- is the job of JavaScript, CSS, or other code in your pages. With XMLHttpRequest ready for use, now you can make a request to a server.

Welcome to the sandbox


Ajax has a sandbox security model. As a result, your Ajax code (and specifically, the XMLHttpRequest object) can only make requests to the same domain on which it's running. A lot regarding to security will be learnt in future upcoming articles, but for now realize that code running on a local machine can only make requests to server-side scripts on that local machine. If an Ajax code running on www.xyz.com, it must make requests to scripts that run on www.xyz.com.

Setting the server URL


The first thing to be determined is the url of the server to connect. This isn't specific to Ajax -- obviously you should know how to construct a URL by now -- but is still essential to making a connection. In most applications, you'll construct this URL from some set of static data combined with data from the form your users work with. For example, Listing below shows some JavaScript that grabs the value of the phone number field and then constructs a URL using that data.



Listing.. Building a request URL

<script language="javascript" type="text/javascript">

var request = false;

try {

request = new XMLHttpRequest();

} catch (trymicrosoft) {

try {

request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (othermicrosoft) {

try {

request = new ActiveXObject("Microsoft.XMLHTTP");

} catch (failed) {

request = false;

}

}

}



if (!request)

alert("Error initializing XMLHttpRequest!");



function getInfo() {

var phone = document.getElementById("phone").value;

var url = "/lookupCustomer.php?phone=" + escape(phone);


}

</script>


Nothing here should trip up. First, the code creates a new variable named phone and assigns the value of the form field with an ID of phone. Listing below shows the HTML for this particular form in which you can see the phone field and its id attribute.


Listing.. The form

<body>

<p><img src="Site Logo.png" alt="Site Name " /></p>

<form action="POST">

<p>Enter your phone number:

<input type="text" size="14" name="phone" id="phone"
onChange="getInfo();" />


</p>

<p>Your order will be delivered to:</p>

<div id="address"></div>

<p>Type your order in here:</p>

<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>

<p><input type="submit" value="Order" id="submit" /></p>

</form>

</body>

Also notice when phone number changed or entered, getInfo() method gets fired shown in Listing above. That method then grabs the number and uses it to construct a URL string stored in the 'url' variable. Remember: Since Ajax code is sandboxed and can only connect to the same domain, one need not have a domain name in your URL. In this example, the script name is lookupCustomer.php. Finally, the phone number is appended to this script as a GET parameter: "phone=" + escape(phone).

Here, escape method is to send the clear text correctly. For example, any spaces in the phone number are converted to "%20" characters, making it possible to pass the characters along in the URL.



Similarly according to requirement, any number of parameters can be added to the query string seperating them with " & ".

Opening the request


With a URL to connect to, request could be configured. This will be accomplished using open() method on your XMLHttpRequest object. This method takes as many as five parameters:

  1. request-type: The type of request to send. Typical values are GET or POST, but you can also send HEAD requests.

  2. url: The URL to connect.

  3. asynch: True if you want the request to be asynchronous and false if it should be a synchronous request. This parameter is optional and defaults to true.

  4. username: If authentication is required, you can specify the username here. This is an optional parameter and has no default value.

  5. password: If authentication is required, you can specify the password here. This is an optional parameter and has no default value.


Typically, first three will be used. In fact, even when we want to send an asynchronous request, we should specify "true" as the third parameter.

That's the default setting, but it's a nice bit of self-documentation to always indicate if the request is asynchronous or not.

Put it all together; end up with a line that looks a lot like Listing below.

Listing.. Open the request

function getInfo() {

var phone = document.getElementById("phone").value;

var url = "/lookupCustomer.php?phone=" + escape(phone);

request.open("GET", url, true);

}



Does open() open?


Internet developers disagree about what exactly the open() method does. It does not actually open a request. If we need to monitor the network and data transfer between your XHTML/Ajax page and the script that it connects to, we wouldn't see any traffic when the open() method is called. It's unclear why the name was chosen, but clearly it is not a good choice.

Once the URL figured out, then this is pretty trivial. For most requests, using GET is sufficient (we will see the situations in which we may want to use POST in future articles); that, along with the URL, is all we need to use open().

A teaser on asynchronicity


Later in the series , significant time will be spent on writing and using asynchronous code. But one should have an idea of why that last parameter in open() is so important.

In a normal request/response model; think Web 1.0 here, the client makes a request to the server.

That request is synchronous; in other words, the client waits for a response from the server.

While the client is waiting, we usually get at least one of several forms of notification that you're waiting:

  • An hourglass (on Windows).

  • A spinning beachball (on Mac machines).

  • The application essentially freezes and sometimes the cursor changes.


This is what makes Web applications in particular feel clunky or slow; the lack of real interactivity. When you push a button, your application essentially becomes unusable until the request you just triggered is responded to. If we've made a request that requires extensive server processing, that wait might be significant (at least for today's multi-processor, DSL, no-waiting world).
An asynchronous request though, does not wait for the server to respond.

You send a request and then your application continues on. Users can still enter data in a Web form, click other buttons, even leave the form.

There will be no freeze of application. The server quietly responds to the request and when it's finished, it let's the original requestor know that it's done (it'll be seen in a moment).

The end result is an application that doesn't feel clunky or slow, but instead is responsive, interactive, and makes feel faster.

This is just one component of Web 2.0, but it's a very important one. All the slick GUI components and Web design paradigms can't overcome a slow, synchronous request/response model.

Sending the request


Once we configure the request with open(), we are ready to send the request. Fortunately, the method for sending a request is named more properly than open(); it's simply called send().
send() takes only a single parameter, the content to send. But before you think too much on that, recall that you are already sending data through the URL itself:

var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);

Although you can send data using send(), we can also send data through the URL itself.

In fact, in GET requests (which will constitute as much as 80 percent of your typical Ajax usage), it's much easier to send data in the URL.

When we start to send secure information or XML, then we need to look at sending content through send(); both secure data and XML messaging could be used in a later article in this series.

When you don't need to pass data along through send(), then just pass null as the argument to this method.

So, to send a request in the example you've seen throughout this article, that's exactly what is needed (see Listing below).
Listing.. Sending the request

function getCustomerInfo() {

var phone = document.getElementById("phone").value;

var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);

request.open("GET", url, true);

request.send(null);

}

Specifying a callback method


At this point, we have done very little that feels new, revolutionary, or asynchronous.

Granted, that little keyword "true" in the open() method sets up an asynchronous request. But other than that, this code resembles programming with Java servlets and JSPs, PHP, or Perl. So what's the big secret to Ajax and Web 2.0?

The secret revolves around a simple property of XMLHttpRequest called onreadystatechange.

First, be sure to understand the process that is created in this code (review Listing above if needed). A request is set up and then made.

Additionally, because this is an asynchronous request, the JavaScript method (getInfo() in the example) will not wait for the server. So the code will continue; in this case, that means that the method will exit and control will return to the form.

Users can keep entering information and the application isn't going to wait on the server.

This creates an interesting question, though:

What happens when the server has finished processing the request?

The answer, at least as the code stands right now, is nothing! Obviously, that's not good, so the server needs to have some type of instruction on what to do when it's finished processing the request sent to it by XMLHttpRequest.

Referencing a function inJavaScript. Since JavaScript is a loosely typed language and you can reference just about anything as a variable.


So if you declare a function called updatePage(), JavaScript also treats that function name as a variable. In other words, you can reference the function in your code as a variable named updatePage

This is where that onreadystatechange property comes into play.

This property allows us to specify a callback method. A callback allows the server to (can you guess?) call back into the web page's code. It gives a degree of control to the server, as well; when the server finishes a request, it looks in the XMLHttpRequest object and specifically at the onreadystatechange property.

Whatever method is specified by that property is then invoked. It's a callback because the server initiates calling back into the Web page; regardless of what is going in the Web page itself.

For example, it might call this method while the user is sitting in her chair, not touching the keyboard; however, it might also call the method while the user is typing, moving the mouse, scrolling, clicking a button ... it doesn't matter what the user is doing.

This is actually where the asynchronicity comes into play: The user operates the form on one level while on another level, the server answers a request and then fires off the callback method indicated by the onreadystatechange property. So you need to specify that method in your code as shown in Listing below



Listing.. Set a callback method

function getCustomerInfo() {

var phone = document.getElementById("phone").value;


var url = "/lookupCustomer.php?phone=" + escape(phone);

request.open("GET", url, true);

request.onreadystatechange = updatePage;


request.send(null);


}

Pay close attention to where in the code this property is set; it's before send() is called. You must set this property before the request is sent, so the server can look up the property when it finishes answering a request. All that's left now is to code the updatePage() which is the focus of the last section in this article.

Handling server responses


When a request is made, your user works happily in the web form (while the server handles the request), and now the server finishes up handling the request. The server looks at the onreadystatechange property and figures out what method to call. Once that occurs, one can think of your application as any other app, asynchronous or not.

In other words, we don't have to take any special action writing methods that respond to the server; just change the form, take the user to another URL, or do whatever else to be done in response of the Server.

In this section, we'll focus on responding to the server and then taking a typical action; changing on the fly part of the form the user sees.

Callbacks and Ajax



We've already seen how to let the server know what to do when it's finished:

Set the onreadystatechange property of the XMLHttpRequest object to the name of the function to run.

When the server has processed the request, automatically that function will be called. We don't need to worry about any parameters to that method. we'll start with a simple method like in Listing.

Listing.. Code the callback method

<script language="javascript" type="text/javascript">

var request = false;

try {

request = new XMLHttpRequest();

} catch (trymicrosoft) {

try {

request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (othermicrosoft) {

try {

request = new ActiveXObject("Microsoft.XMLHTTP");

} catch (failed) {

request = false;

}

}

}



if (!request)

alert("Error initializing XMLHttpRequest!");



function getInfo() {

var phone = document.getElementById("phone").value;

var url = "/lookupCustomer.php?phone=" + escape(phone);

request.open("GET", url, true);

request.onreadystatechange = updatePage;

request.send(null);

}

/*This function is called after server has completed its work regarding to response*/

function updatePage() {

alert("Server is done!");

}

<script>

This just displays a handy alert; to intimate when the server is done. Try this code in your own page, save the page, and then pull it up in a browser (if you want the XHTML from this example, refer back to Listing above). When a phone number and field is left, alert popup should be seen; but click OK and it pops up again ... and again.

Depending on your browser, you'll get two, three, or even four alerts before the form stops popping up alerts. So what's going on? It turns out that you haven't taken into account the HTTP ready state, an important component of the request/response cycle.

HTTP ready states



Earlier, I said that the server, once finished with a request, looks up what method to call in the onreadystatechange property of XMLHttpRequest. That's true, but it's not the whole truth. In fact, it calls that method every time the HTTP ready state changes. So what does that mean? Well, we've got to understand HTTP ready states first.

An HTTP ready state indicates the state or status of a request. It's used to trace if a request has been started, if it's being answered, or if the request/response model has completed. It's also helpful in determining whether it's safe to read whatever response text or data that a server might have supplied. There are 5 Ready states in AJAX Applications:

  • 0: The request is uninitialized (before you've called open()).

  • 1: The request is set up, but hasn't been sent (before you've called send()).

  • 2: The request was sent and is being processed (you can usually get content headers from the response at this point).

  • 3: The request is being processed; often some partial data is available from the response, but the server hasn't finished with its response.

  • 4: The response is complete; we have server's response and use it.


As with almost all cross-browser issues, these ready states are used somewhat inconsistently. You might expect to always see the ready state move from 0 to 1 to 2 to 3 to 4, but in practice, that's rarely the case. Some browsers never report 0 or 1 and jump straight to 2, then 3, and then 4. Other browsers report all states. Still others will report ready state 1 multiple times. As we saw in the last section, the server called updatePage() several times and each invocation resulted in an alert box popping up; probably which is not intended.

For Ajax programming, the only state you need to deal with directly is readyState 4, indicating that a server's response is complete and it's safe to check the response data and use it. To account for this, the first line in your callback method should be as shown in Listing below.

Listing.. Check the ready state

function updatePage() {

if (request.readyState == 4)

alert("Server is done!");

}

This change checks to ensure that the server really is finished with the process. Try running this version of the Ajax code and you should only get the alert message one time, which is as it should be.

HTTP status codes


Despite the apparent success of the code in Listing above, there's still a problem;

What happens if server finishing processing and reports an error?

Remember, that server-side code should care if it's being called by Ajax, a JSP, a regular HTML form, or any other type of code; it only has the traditional Web-specific methods of reporting information. And in the Web world, HTTP codes can deal with the various things that might happen in a request.

For example, we've certainly entered a request for a URL, typed the URL incorrectly, and received a 404 error code to indicate a page is missing.

This is just one of many status codes that HTTP requests can receive as a status. In each of these cases, these are codes that result from a completed response. In other words, the server fulfilled the request (meaning the HTTP ready state is 4), but is probably not returning the data expected by the client.
In addition to the ready state then, we also need to check the HTTP status. we are looking for a status code of 200 which simply means okay. With a ready state of 4 and a status code of 200, we are ready to process the server's data and that data should be what we've asked for. Add another status check to your callback method as shown in Listing below.
Listing.. Check the HTTP status code

function updatePage() {

if (request.readyState == 4)

if (request.status == 200)

alert("Server is done!");

}

To add more robust error handling, with minimal complication; we might add a check or two for other status codes; check out the modified version of updatePage() in Listing below.

Listing.. Adding some light error check

function updatePage() {

if (request.readyState == 4)

if (request.status == 200)

alert("Server is done!");

else if (request.status == 404)

alert("Request URL does not exist");

else

alert("Error: status code is " + request.status);

}

Now change the URL in your getInfo() to a non-existent URL and see what happens. An alert should say URL does not exists; perfect! This's hardly going to handle every error condition, but it's a simple change that covers 80 percent of the problems that can occur in a typical Web application.

Reading the response text


Now that we make sure the request was completely processed (through the ready state) and the server gave you a normal, okay response (through the status code), one can finally deal with the data sent back by the server. This is conveniently stored in the responseText property of the XMLHttpRequest object.

Details about what the text in responseText looks like, in terms of format or length, is left intentionally displayed. This allows the server to set this text to virtually anything. For instance, one script might return comma-separated values, another pipe-separated values (the pipe is the | character), and another may return one long string of text. It's all up to the server.

In the case of the example used in this article, the server returns a customer's last order and then their address, separated by the pipe symbol. The order and address are both then used to set values of elements on the form; Listing below shows the code that updates the display.
Listing.. Dealing with server's response

function updatePage() {

if (request.readyState == 4) {

if (request.status == 200) {

var response = request.responseText.split("|");

document.getElementById("order").value = response[0];

document.getElementById("address").innerHTML =
response[1].replace(/\n/g, "
");

} else

alert("status is " + request.status);

}

}



First, the responseText is pulled and split on the pipe symbol using the JavaScript split() method. The resulting array of values is dropped into response. The first value, the customer's last order; is accessed in the array as response[0] and is set as the value of the field with an ID of "order." The second value in the array, at response[1], is the customer's address and it takes a little more processing. Since the lines in the address are separated by normal line separators (the "\n" character), the code needs to replace these with XHTML-style line separators, <br /> s. That's accomplished through the use of the replace() function along with a regular expression. Finally, the modified text is set as the inner HTML of a div in the HTML form. The result is that the form suddenly is updated with the customer's information.

Before this article closed up; another important property of XMLHttpRequest is called responseXML. Guess what that property contains?

An XML response in the event that the server chooses to respond with XML. Dealing with an XML response is quite different than dealing with plain text and involves parsing, the Document Object Model (DOM), and several other considerations.

More will be learnt in future articles regarding to XML and DOM parsing. Still, because responseXML commonly comes up in discussions surrounding responseText, it's worth mentioning here.

For many simple Ajax applications, responseText is all you need, but you'll soon learn about dealing with XML through Ajax applications as well.
Saturday, January 24, 2009

Ajax it's a powerful approach to building Web sites and it's not nearly as hard to learn as an entire new language.
It is mainly based on Javascript and XML
Before seeing what Ajax is, though, let's spend just a few moments understanding what Ajax does.

When an application is written today, we have two basic choices:

  • Desktop applications
    Desktop applications usually installed completely on your computer. They might use the Internet to download updates, but the code that runs these applications resides on your desktop.

  • Web applications
    There's no surprise here -- run on a Web server somewhere and you access the application with your Web browser.



More important than where the code for these applications runs, is how they do interact. Desktop applications are usually pretty fast (they're running on your computer; you're not waiting on an Internet connection), & have great user interfaces (usually interacting with your operating system), and are incredibly dynamic.

On the other hand, Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (yahoo and google). However, with the power of the Web comes waiting -- waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and to generate a new page.
As you might already be suspecting, Ajax attempts to reduce the gap between the functionality and interactivity of a desktop application and the always-updated Web application.
Here dynamic user interfaces and fancy controls can be used.
So what are you waiting for? Start looking at Ajax and how to turn your clunky Web interfaces into responsive Ajax applications.

Here are the basic technologies involved in Ajax applications:

  • HTML is used to build Web forms and identify fields for use in the rest of your application.

  • JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.

  • DHTML, or Dynamic HTML, helps you update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.

  • DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.


The XMLHttpRequest object

The first object you want to understand is probably the one that's newest to you; it's called XMLHttpRequest. This is a JavaScript object and is created as simply as shown below..
Listing.. Create a new XMLHttpRequest object

<script language="javascript" type="text/javascript">

var xmlHttp = new XMLHttpRequest();

</script>

This object will be discussed in next part, but for now realize this object that handles all your server communication. Before going forward, stop and think about that -- it's the JavaScript technology through the XMLHttpRequest object that talks to the server. That's not the normal application flow and it's where Ajax gets much of its magic.Getting a Request object
With a basic overview under your belt, you're ready to look at a few specifics. Since XMLHttpRequest is central to Ajax applications -- and probably new to many of you -- I'll start there. As you saw in Listing 1, it should be pretty easy to create this object and use it, right? Wait a minute.
Remember those pesky browser wars from a few years back and how nothing worked the same across browsers? Well, believe it or not, those wars are still going on albeit on a much smaller scale. And, surprise: XMLHttpRequest is one of the victims of this war. So you'll need to do a few different things to get an XMLHttpRequest object going. I'll take your through it step by step.
Working with Microsoft browsersMicrosoft's browser, Internet Explorer, uses the MSXML parser for handling XML (you can find out more about MSXML in Resources). So when you write Ajax applications that need to work on Internet Explorer, you need to create the object in a particular way.
However, it's not that easy. MSXML actually has two different versions floating around depending on the version of JavaScript technology installed in Internet Explorer, so you've got to write code that handles both cases. Look at Listing below for the code that you need to create an XMLHttpRequest on Microsoft browsers.
Listing.. Create an XMLHttpRequest object on Microsoft browsers

var xmlHttp = false;
try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

All of this won't make sense , but its OK. You'll dig into JavaScript programming, error handling, conditional compilation, and more before this series is finished. For now, you want to get two core lines into your head:
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
and
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");.

In whole, this code tries to create the object using one version of MSXML; if that fails, it then creates the object using the other version. Nice, huh? If neither of these work, the xmlHttp variable is set to false, to tell your code know that something hasn't worked. If that's the case, you've probably got a non-Microsoft browser and need to use different code to do the job.
Dealing with non-Microsoft browsers
If Internet Explorer isn't your browser of choice or you write code for non-Microsoft browsers, then you need different code. In fact, this is the really simple line of code you saw back in first Listing..
var xmlHttp = new XMLHttpRequest object;
This simpler line creates an XMLHttpRequest object in Mozilla, Chrome, Safari and several browsers any form or fashion.
The key is to support all browsers. Who wants to write an application that works just on Internet Explorer or an application that works just on non-Microsoft browsers? Worse yet, do you want to write your application twice? Of course not! So your code combines support for both Internet Explorerand non-Microsoft browsers. Listing below shows the code to do that.
Listing... Create an XMLHttpRequest object the multi-browser way

/* Create a new XMLHttpRequest object to talk to the Web server */

var xmlHttp = false;

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {

xmlHttp = new XMLHttpRequest();

}

Focus exclusively on XMLHttpRequest. The core of this code breaks down into three steps:

1. Create a variable, xmlHttp, to reference the XMLHttpRequest object that you will create.

2. Try and create the object in Microsoft browsers:

* Try and create the object using the Msxml2.XMLHTTP object.

* If that fails, try and create the object using the Microsoft.XMLHTTP object.

3. If xmlHttp still isn't set up, create the object in a non-Microsoft way.

At the end of this process, xmlHttp should reference a valid XMLHttpRequest object, no matter what browser your users run.
So you now understand Ajax and have a basic idea about the XMLHttpRequest object and how to create it.
If read read closely, one can realize that it's the JavaScript technology that talks to any Web application on the server rather than your submitting HTML form to application.
What's the missing piece? How to actually use XMLHttpRequest. Since this is critical code that you'll use in some form in every Ajax application you write, take a quick tour through what a basic request/response model with Ajax looks like.
Making a request

You have your shiny new XMLHttpRequest object; now take it for a spin. First, you need a JavaScript method that your Web page can call (like when a user types in text or selects an option from a menu). Then, you'll follow the same basic outline in almost all of your Ajax applications:

  1. Get whatever data you need from the Web form.

  2. Build the URL to connect to.

  3. Open a connection to the server.

  4. Set up a function for the server to run when it's done.

  5. Send the request.


Listing is a sample of an Ajax method that does these very things, in this order:
Listing.. Make a request with Ajax

function callServer() {

// Get the city and state from the web form

var city = document.getElementById("city").value;

var state = document.getElementById("state").value;

// Only go on if there are values for both fields

if ((city == null) || (city == "")) return;

if ((state == null) || (state == "")) return;

// Build the URL to connect to

var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);

// Open a connection to the server

xmlHttp.open("GET", url, true);

// Setup a function for the server to run when it's done

xmlHttp.onreadystatechange = updatePage;

// Send the request

xmlHttp.send(null);

}


A lot of this is self-explanatory. The first bit of the code uses basic JavaScript code to grab the values of a few form fields. Then the code sets up a PHP script as the destination to connect to. Notice how the URL of the script is specified and then the city and state (from the form) are appended to this using simple GET parameters.

Next, a connection is opened; here's the first place you see XMLHttpRequest in action again. The method of connection is indicated (GET), as well as the URL to connect to. The final parameter, when set to true, requests an asynchronous connection (thus making this Ajax). If you used false, the code would wait around on the server when the request was made and not continue until a response was received. By setting this to true, your users can still use the form (and even call other JavaScript methods) while the server is processing this request in the background.

The onreadystatechange property of xmlHttp (remember, that's your instance of the XMLHttpRequest object) allows you to tell the server what to do when it does finish running (which could be in five minutes or five hours). Since the code isn't going to wait around for the server, you'll need to let the server know what to do so you can respond to it. In this case, a specific method -- called updatePage() -- will be triggered when the server is finished processing your request.

Finally, send() is called with a value of null. Since you've added the data to send to the server (the city and state) in the request URL, you don't need to send anything in the request. So this fires off your request and the server can do what you asked it to do.

If you don't get anything else out of this, notice how straightforward and simple this is! Other than getting the asynchronous nature of Ajax into your head, this is relatively simple stuff. You'll appreciate how it frees you up to concentrate on cool applications and interfaces rather than complicated HTTP request/response code.

The code at last Listing is about as easy as it gets. The data is simple text and can be included as part of the request URL. GET sends the request rather than the more complicated POST. There's no XML or content headers to add, no data to send in the body of the request -- this is Ajax simplicity, in other words.

Don't get panic; things will become more complicated as series progresses. You'll learn sending POST requests, setting headers and content types, encoding XML in request, how to add security to your request so on!

Don't worry about this stuff for now; get your concentration around basics, and sooner you could build up a whole set of Ajax tools.

Handling the response


Now time to handle the servers' response. You really only need to know two things at this point:

  • Don't do anything until the xmlHttp.readyState property is equal to 4.

  • The server will stuff it's response into the xmlHttp.responseText property.


The first of these ready states is going to take up the bulk of the next article. For now, simply check for a certain value (4), things will work.
The second one using xmlHttp.responseText property for getting server's response -- is easy. Next Listing provides an example of a method that the server can call based on the values sent in previous listing.
Listing.. Handle the server's response

function updatePage() {

if (xmlHttp.readyState == 4) {

var response = xmlHttp.responseText;

document.getElementById("zipCode").value = response;

}

}

This code is not difficult or complicated. Waits until server sends with proper readyState and then uses the value that the server returns to set the value of another form field; with this suddenly a pincode will appear in the control provided for it -- but the user never had to click a button!. That's the feel of desktop that is described earlier. Responsiveness, a dynamic feel, and more, or less like a Javacsript code.
Readers might notice that the pincode field is normal text field. Once the server returns the ZIP code and the updatePage() method sets the value of that field with the city/state ZIP code, users can override the value.
Wednesday, January 14, 2009
PHP supports eight primitive types.

Four scalar types
  1. boolean
  2. integer
  3. float (floating-point number, or 'double')
  4. string

Two compound types
  1. Array
  2. object
And finally two special types:
  1. resource
  2. NULL


We introduce some pseudo-types for readability:
  1. mixed
  2. number
  3. callback

You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.

The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

Note: If you want to check out the type and value of a certain expression, use var_dump().


If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:

?php

$a_bool = TRUE; // a boolean

$a_str = "foo"; // a string

$a_str2 = 'foo'; // a string

$an_int = 12; // an integer
echo gettype($a_bool); // prints: boolean

echo gettype($a_str); // prints: string

// If this is an integer, increment it by four

if (is_int($an_int)) {

$an_int += 4;

}
// If $bool is a string, print it out

// (does not print out anything)

if (is_string($a_bool)) {

echo "String: $a_bool";

}

?>

If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time.
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP.You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Adabas D InterBase PostgreSQL
dBase FrontBase SQLite
Empress mSQL Solid
FilePro (read-only) Direct MS-SQL Sybase
Hyperwave MySQL Velocis
IBM DB2 ODBC Unix dbm
Informix Oracle (OCI7 and OCI8)
Ingres Ovrimos


We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...

Sunday, January 11, 2009


PHP (Recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

Simple answer, but what does that mean? An example:


Introductory Example

<HTML>
Example
<body>
This is normal text (HTML)

<?php
echo "Hi: PHP Line";
?>

</body>
</HTML>


Notice how this is different from a script written in other languages like Perl or C -- instead of writing a program with lots of commands to output HTML, you write an HTML script with some embedded code to do something (in this case, output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode".


What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.

Although PHP's development is focused on server-side scripting, you can do much more with it.

Few Points to ponder:


  • PHP Files are generally saved with extension .php

  • PHP code must be embedded in between start and end tags

  • Mainly two types of tags available for PHP they are
    1."<?" and "?>" - short hand tag
    2."<?php" and "?>" normal tag

  • * "<%" and "%>" - general script tags(ASP, JSP etc..) can be enabled by configuring in web server.
  • In PHP all the variables must start with a "$" symbol.

  • If $ symbol is missed in front of a variable, it would be treated as dirty string.(T_String).



In the next section we will know about Variables and Data Types