Professional Documents
Culture Documents
BACHELOR of TECHNOLOGY
In
Dept. of CSE
1 Venjaramood
MACE,
Contents
1. Introduction ............................................................................................... 3 2. Defining Ajax ............................................................................................ 4 3. The Classic Model Vs Ajax Model ........................................................... 5 3.1.The Classic Web Application Model .......................................... 5 3.2.How Ajax is Different ................................................................. 5 4. Examples- What Can You Do with Ajax? .............................................. 8 4.1.RICO AJAX Search ..................................................................... 8 4.2.Searching in real time with live searches .................................... 9 4.3.Easy typing with auto-complete ................................................. 10 4.4.Chatting with friends .................................................................. 10 4.5.Dragging and dropping with Ajax .............................................. 11 4.6.Gaming with Ajax ...................................................................... 12 4.7.Modifying Web pages on the fly ................................................ 13 4.8.Google Maps and Ajax ............................................................... 14 4.9.Ajax-enabled pop-up menus ....................................................... 15 5. Requirements for Ajax ............................................................................. 16 5.1.XMLHttpRequest Object ........................................................... 16 5.2.JavaScript ................................................................................... 17 6. The Ingredients of Ajax ............................................................................ 18 6.1.Introduction ................................................................................ 18 6.2.XMLHttpRequest Object ........................................................... 18 6.3.Document Object Model (DOM) ............................................... 20
6.3.1. Two Approaches for Updating the Page ...........................21 6.3.2. Ajax Page Update GotchasBrowser Memory Leaks ..... 21
Dept. of CSE
2 Venjaramood
MACE,
7. Ajaxifying Your Web Application .......................................................... 34 7.1.Creating an XMLHttpRequest object ........................................ 34 7.2.Sending an Ajax request to the Server ....................................... 36 7.3.Receiving Ajax responses from the server ................................. 37
7.3.1. The onreadystatechange Property .................................... 37
8. Try it your self A Simple Example ....................................................... 38 9. Conclusion ................................................................................................. 40 9.1.When you should use Ajax ........................................................ 40 9.2.Advantages of Ajax ................................................................... 40
9.2.1. Reduced Bandwidth usage ................................................ 40 9.2.2. Separation of data, format, style, and function ............... 40
Dept. of CSE
3 Venjaramood
MACE,
1. Introduction
When you write an application today, you have two basic choices: Desktop applications Web applications Both of these are familiar to most of us; desktop applications usually come on a CD (or sometimes are downloaded from a Web site) and install completely on your computer. They might use the internet to download updates, but the code that runs these applications resides on your computer. Where as Web applications run on a Web server somewhere and you access the application with your Web browser. More important than where the code for these applications run, though, is how the applications behave and how you interact with them. Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (have a look at Amazon.com and eBay). Web opens an unlimited range of possibility to the application developer. However, desktop applications have a richness and responsiveness that has always seemed out of reach on the Web. The same simplicity that enabled the Webs rapid expansion and growth also creates a gap between the experiences we can provide and the experiences users can get from a desktop application.
Dept. of CSE
4 Venjaramood
MACE,
Now that gap is closing. Take a look at Google Suggest. Watch the way the suggested terms update as you type, almost instantly. Now look at Google Maps. Zoom in. Use your cursor to grab the map and scroll around a bit. Again, everything happens almost instantly, with no waiting for pages to reload. Google Suggest and Google Maps are two examples of a new approach to Web applications now known as Ajax. The name, Ajax is shorthand for Asynchronous JavaScript + XML, and it represents a fundamental shift in whats possible on the Web. Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. You can use dynamic user interfaces and fancier controls like youd find on a desktop application, but its now available to you on a Web application.
2. Defining Ajax
Ajax isnt a new technology by itself. Its really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates: standards-based presentation using XHTML and CSS; dynamic display and interaction using the DOM(Document Object Model); data interchange and manipulation using XML and XSL; asynchronous data retrieval using XMLHttpRequest; and JavaScript binding everything together.
AJAX (Asynchronous JavaScript and XML) the term has been around for just two years created by Jesse James Garrett in 2005 in his famous essayAjax: A New Approach to Web Applications . The technologies that make Ajax work, however, have been around for almost a decade.
Dept. of CSE
5 Venjaramood
MACE,
Trivia: So is it AJAX or Ajax? In Jesse Garretts original article that coined the term, it was AJAX. The X in AJAX really stands for XMLHttpRequest, though, and not XML. He later conceded that Ajax should be a word and not an acronym and updated his article to reflect his change in heart. So Ajax is the correct casing. Lets break these down and get a better idea of what each does. We will focus on becoming familiar with these components and technologies and then, later we may go in to details of each of them and how they play their role in making Ajax possible. Ajax relies on XMLHttpRequest, CSS, DOM and other technologies; the main characteristic of AJAX is its asynchronous nature, which makes possible to send and receive data from the server without having to refresh the page. Common Ajax implementations can be found in various languages and libraries like ActiveX, Flash and Java applet. I prefer to focus on JavaScript language, because is considered the formal standard in Web 2.0 application development.
Dept. of CSE
6 Venjaramood
MACE,
Obviously, if we were designing the Web from scratch for applications, we wouldnt make users wait around. Once an interface is loaded, why should the user interaction come to a halt every time the application needs something from the server? In fact, the user neednt see the application go to the server at all. This is where the ability to communicate asynchronously with the server becomes relevant.
Dept. of CSE
7 Venjaramood
MACE,
Figure 1: The traditional model for web applications (left) compared to the Ajax model (right). Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesnt require a trip back to the server such as simple data validation, editing data in memory, and even some navigation the engine handles on its own. If the engine needs something from the server in order to respond if its submitting data for processing, loading additional interface code, or retrieving new data the engine makes those requests asynchronously, usually using XML, without stalling a users interaction with the application.
Dept. of CSE
8 Venjaramood
MACE,
Figure 2: The synchronous interaction pattern of a traditional web application (top) compared with the asynchronous pattern of an Ajax application (bottom).
Dept. of CSE
9 Venjaramood
MACE,
Dept. of CSE
10 Venjaramood
MACE,
Figure 3: RICO AJAX Search- An Ajax-enabled Yahoo! search. Thats the Ajax difference. In the case of ordinary Yahoo! search, you get a new page with search results, but to see more than ten results, a user has to keep loading pages. Where as, in the RICO-AJAX Search, everything happens on the same page. No page reloads; no fuss, no muss. You can find plenty of such Ajax on the http://openrico.org Web site. If youre inclined to, browse around and discover all the good stuff there.
Dept. of CSE
12 Venjaramood
MACE,
Dept. of CSE
13 Venjaramood
MACE,
Figure 6: An Ajax based chat application. There are plenty of Ajax-based chat rooms around. Take a look at http://treehouse.ofb.net/chat/?lang=en for another example. You can see another great example for Ajax based chat application along with Gmail. In fact, Gmail is filled with cool examples for Ajax applications.
Dept. of CSE
14 Venjaramood
MACE,
Dept. of CSE
15 Venjaramood
MACE,
Dept. of CSE
16 Venjaramood
MACE,
Dept. of CSE
17 Venjaramood
MACE,
Dept. of CSE
19 Venjaramood
MACE,
5.2. JavaScript
As I mentioned earlier, the XMLHttpRequest built-in to the browser makes Ajax possible, but how do web pages use this object and what does it really do? This is where we first see JavaScript added to the Ajax equation, because to use the XMLHttpRequest on a web page we must write some JavaScript. The XMLHttpRequest, like any other JavaScript object, works because the browsers JavaScript parser (or engine) recognizes the object in the code and knows how to process it.
Trivia: Why is JavaScript (and in turn, Ajax) hard to write? In part, it is because every browser handles JavaScript just a little differently. Any web browser that wants to support JavaScript must provide its own engine to parse JavaScript commands and perform the correct browser actions. Firefox uses the open source JavaScript engine called SpiderMonkey, Safari uses an engine called JavaScriptCore, and Opera uses its own proprietary engine. IEs engine actually processes JScript", Microsofts own brand (literally) of JavaScript created (in part) to avoid copyright issues with JavaScript trademark holder Sun. Even though JavaScript is standardized by Ecma, each engine does things a little differently. That means solid JavaScript or Ajax programming must be done in a way that accounts for these differences.
Thus another important requirement for Ajax applications to work is browser support for executing JavaScript in your web pages. Most of the modern browsers provide support for JavaScript through built-in parsers that can identify and execute JavaScript statements. However, the browsers security settings may sometimes block the execution of JavaScript in web pages. To overcome such situations Ajax application developers may have to use advanced techniques.
Dept. of CSE
20 Venjaramood
MACE,
Dept. of CSE
21 Venjaramood
MACE,
XPath or regular DOM node tree methods (like getElementByTag, etc.). responseText: contains the raw text response from the server If there is an error, we are also interested in this property: statusText: contains the text describing our response status code. If we receive a HTTP response code of 404, for instance, the statusText would contain Not Found.
Trivia: HTTP Status Code 304 Http Status code 304 is technically a valid response code that could be returned from the server when performing a GET. It indicates that the page has not been changed and the page in the browsers cache should be used. In Firefox, the XMLHttpRequest status property will return 200 if the server responds with 200 or 304. IE will also return status code 200 in the XMLHttpRequest GET response, so a solid implementation of your callback function does not need to check for both codes. XMLHttpRequest also provides methods required for accomplishing asynchronous HTTP communication with a server. The important methods are; open (Request Method, URL, Async. Flag) You must supply three parameters to the open method: 1. Request Method: can be either POST or GET (case sensitive). The POST and GET values should be familiar as they are normal Http concepts. Like normal Http requests, GETs are processed slightly faster by the server than POSTs, but they do not allow any data to be sent to the server (other than what you can fit into the URLs querystring) 2. URL: the request URL (must be in your domain)
Dept. of CSE
22 Venjaramood
MACE,
3. Async Flag: a Boolean value indicating if the request should asynchronous. Thats right. You can actually use the XMLHttpRequest to do SJAX (Synchronous JavaScript). This is rarely done for obvious reasons, so the third parameter in the open method will almost always be true. Important note: even though we can use open method to open our connection, it doesnt send our request to the server. You often hear the term callback replace the term postback when you work with Ajax. Thats because Ajax uses a callback function to catch the servers response when it is done processing your Ajax request. Another important property of XHR object is onreadystatechange, which holds a reference to the Ajax call back function that catches and processes the servers response. If the request method is POST we must set the Content-Type header. For that we use setRequestHeader method. To send the Ajax request to the server with the POST data we use the send method.
Unlike PostBacks (which update the entire page), Ajax callbacks only update the portions of the page you programmatically update with JavaScript. That means you have to handle changes to all the page elements, the page head, the hidden page elements (like ViewState) and even the page title. Furthermore, since the page is not being reloaded, you also have to handle the execution of any page load JavaScript manually. You can see how this quickly gets tricky.
Trivia: Why is manipulating the DOM hard? Every browser has its own JavaScript rendering engine and it has its own DOM layout engine. The W3C standardized the DOM in 1998, but browsers have been slow to provide uniform support of the W3C standards. Microsofts IE uses a DOM layout engine called Trident (or MSHTML), all Mozilla based browers (including Firefox and Netscape) use the open source Gecko layout engine, Safari uses Apples WebCore, and Opera uses its own proprietary Presto layout engine. All engines support DOM 1.0, but support for the later DOM 2.0 and 3.0 is still spotty. 6.3.1. Two Approaches for Updating the Page When it comes to updating the page after an Ajax callback, there are two basic approaches: 1) parse information from the server and build the updated controls on the client, or 2) build updated controls on the server and simply swap the old with the new on the client. The first approach can reduce the amount of information that is sent over the Internet during an Ajax update, but the savings is usually offset by the browsers generally slow handling of DOM manipulations.
6.3.2. Ajax Page Update Gotchas - Browser Memory Leaks Browser memory leaks have always existed, but the advent of extremely complex client-side web applications that dont rely on the traditional page navigation model to update the page have made memory
Dept. of CSE 24 Venjaramood MACE,
leaks a problem that cant be ignored. Just like .NET code, browsers have garbage collectors that are supposed to release memory from unused DOM elements (such as elements you remove from the page in an Ajax update). Certain coding patterns, though, can foil the browser garbage collectors and quickly turn your Ajax application into a memory hog.
The most common coding practices that result in memory leaks are: Circular References, Closures, Cross-Page Leaks, and Pseudo Leaks. MSDN has a great article on memory leaks in IE and I encourage you to read it for a full understanding of these leak types (link in References list).
Figure 12: This chart quickly highlights the frequency in which browser memory leaks occur and their relative impact.
Dept. of CSE
25 Venjaramood
MACE,
Trivia: How do you fix a leaking IE? Knowing that browser memory leaks exist is great, but how do you figure out if your application is leaking? A great tool exists, called Drip that enables you to easily observe any IE memory leaks your web application. Originally created by Joel Webber in 2005, Drip is now a SourceForge project that is freely available here: http://outofhanwell.com/ieleak. Even if youre not concerned about fixing memory leaks in your application, its an interesting exercise to use Drip to see how efficiently your application uses system memory.
XML is a markup language where everything has to be marked up correctly, which results in "well-formed" documents. XML was designed to describe data and HTML was designed to display data.
Dept. of CSE
26 Venjaramood
MACE,
Today's market consists of different browser technologies, some browsers run Internet on computers, and some browsers run Internet on mobile phones and hand held devices. The last-mentioned do not have the resources or power to interpret a "bad" markup language. Therefore - by combining HTML and XML, and their strengths, we got a markup language that is useful now and in the future - XHTML. XHTML pages can be read by all XML enabled devices AND while waiting for the rest of the world to upgrade to XML supported browsers, XHTML gives you the opportunity to write "well-formed" documents now, that work in all browsers and that are backward browser compatible !! XHTML is not very different from the HTML 4.01 standard. So, bringing your code up to the 4.01 standard is a good start to get to XHTML standard. In addition, you should start NOW to write your HTML code in lowercase letters, and NEVER skip ending tags (like </p>). The most important differences of XHTML are: XHTML elements must be properly nested XHTML elements must always be closed XHTML elements must be in lowercase XHTML documents must have one root element
6.4.2. CSS (Cascading Style Sheets) HTML tags were originally designed to define the content of a document. They were supposed to say "This is a header", "This is a paragraph", "This is a table", by using tags like <h1>, <p>, <table>, and so on. The layout of the document was supposed to be taken care of by the browser, without using any formatting tags. As the two major browsers - Netscape and Internet Explorer continued to add new HTML tags and attributes (like the <font> tag and the color attribute) to the original HTML specification, it became more and more
Dept. of CSE 27 Venjaramood MACE,
difficult to create Web sites where the content of HTML documents was clearly separated from the document's presentation layout. To solve this problem, the World Wide Web Consortium (W3C), responsible for standardizing HTML - created STYLES in addition to HTML 4.0. Styles sheets define HOW HTML elements are to be displayed, just like the font tag and the color attribute in HTML 3.2. Styles are normally saved in external .css files. External style sheets enable you to change the appearance and layout of all the pages in your Web, just by editing one single CSS document! CSS is a breakthrough in Web design because it allows developers to control the style and layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML element and apply it to as many Web pages as you want. To make a global change, simply change the style, and all elements in the Web are updated automatically. Style sheets allow style information to be specified in many ways. Styles can be specified inside a single HTML element, inside the <head> element of an HTML page, or in an external CSS file. Even multiple external style sheets can be referenced inside a single HTML document. Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority: 1. Browser default 2. External style sheet 3. Internal style sheet (inside the <head> tag) 4. Inline style (inside an HTML element) So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style declared inside the <head> tag, in an external style sheet, or in a browser (a default value).
Dept. of CSE
28 Venjaramood
MACE,
Syntax: The CSS syntax is made up of three parts: a selector, a property and a value: selector {property: value} The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces: Example: body {color: black}
Dept. of CSE
29 Venjaramood
MACE,
<?xml version="1.0"?> <transaction ID="THX1138"> <salesperson>bluemax</salesperson> <order> <product productNumber="3263827"> <quantity>1</quantity> <unitprice currency="standard">3000000</unitprice> <description>Medium Trash Compactor</description> </product> </order> <return></return> </transaction>
Serialized this way, as text, the information is available in any environment in which you might need it. Even without a special application, you can see the content (in bold) and the markup, which describes it. What can I do with XML? Since its introduction, developers have found numerous uses for XML. Here are some resources that give you an idea of how you can put XML to work. Storing data The most obvious use of XML is to store data. XML provides advantages for both data-centric information (such as the data you find in a database) and document-centric information (such as data you store in XML so you can display it differently in different environments.) Web services Web services began as a way to pass non-HTML information over HTTP. They have grown to be the foundation for fields from Ajax, used to add interactivity to Web sites, to today's Service Oriented Architectures (SOA), complex message-based applications. XML is
Dept. of CSE
30 Venjaramood
MACE,
integral to the field of Web services. All of the leading methods of Web services, SOAP, REST, and even XML-RPC, are based in XML. Podcasting and other data syndication One of the most common uses of XML today is in the realm of syndication. Millions of bloggers use RSS feeds to keep up with the latest information on their favorite blogs, and commercial interests have begun taking an interest in podcasting, or distributing audio and video over the internet to devices such as iPods, which also uses XML. Platform-independent configuration and deployment instructions A common place to find XML is behind the scenes of your favorite applications and development environments, where it serves as a common means for creating files of configurations or instructions. Providing configuration instructions in a human-readable XML file enables users to control the behavior of applications much more easily than before.
6.5.2 XSL XSL stands for EXtensible Stylesheet Language. The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML-based Stylesheet Language. HTML uses predefined tags and the meaning of the tags are well understood. The <table> element in HTML defines a table - and a browser knows how to display it. So adding styles to HTML elements is simple. Telling a browser to display an element in a special font or color is easy with CSS. XML does not use predefined tags (we can use any tag-names we like), and the meaning of these tags are not well understood. A <table> element could mean an HTML table, a piece of furniture, or something else - and a browser does not know how to display it. Here XSL describes how the XML document should be displayed.
Dept. of CSE
31 Venjaramood
MACE,
So we may also put it simply as; CSS = HTML Style Sheets where as XSL = XML Style Sheets But in reality XSL is more than a Style Sheet Language. XSL consists of three parts: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents 6.5.3 XSLT = XSL Transformations XSLT is the most important part of XSL. XSLT stands for XSL Transformations. XSLT became a W3C Recommendation 16. November 1999. XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element. With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more. A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-tree. XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents. In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document. XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XQuery and XPointer are both built on XPath expressions.
Dept. of CSE
32 Venjaramood
MACE,
XPath includes over 100 built-in functions. There are functions for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more.
Browser support Nearly all major browsers have support for XML and XSLT. Mozilla Firefox: As of version 1.0.2, Firefox has support for XML and XSLT (and CSS). Mozilla: Mozilla includes Expat for XML parsing and has support to display XML + CSS. Mozilla also has some support for Namespaces. Mozilla is available with an XSLT implementation. Netscape: As of version 8, Netscape uses the Mozilla engine, and therefore it has the same XML / XSLT support as Mozilla. Opera: As of version 9, Opera has support for XML and XSLT (and CSS). Version 8 supports only XML + CSS. Internet Explorer: As of version 6, Internet Explorer supports XML, Namespaces, CSS, XSLT, and XPath. Version 5 is NOT compatible with the official W3C XSL Recommendation.
Dept. of CSE
33 Venjaramood
MACE,
The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996. The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997. The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998, and its development is still in progress. A JavaScript consists of lines of executable computer code that is usually embedded directly into HTML pages. JavaScript is an interpreted language (means that scripts execute without preliminary compilation). Browsers with JavaScript support usually provide built-in interpreters to execute the embedded JavaScript programs.
Trivia: Are Java and JavaScript the Same? NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
6.6.1. What can a JavaScript Do? JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
Dept. of CSE
34 Venjaramood
MACE,
JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer
6.6.2. How to put a JavaScript into an HTML page The HTML <script> tag is used to insert a JavaScript into an HTML page.
<html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>
The code above will produce this output on an HTML page: Hello World!
Dept. of CSE
35 Venjaramood
MACE,
HTML Comments to Handle Older Browsers Browsers that do not support JavaScript will display JavaScript as page content. To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag can be used to "hide" the JavaScript. Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement.
<html> <body> <script type="text/javascript"> <!-document.write("Hello World!"); //--> </script> </body> </html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
6.6.3. Where to Put the JavaScript JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<html> <head> <script type="text/javascript"> .... </script> </head>
Dept. of CSE 36 Venjaramood MACE,
Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
<html> <head> </head> <body> <script type="text/javascript"> .... </script> </body>
Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
Dept. of CSE
37 Venjaramood
MACE,
Using an External JavaScript Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. Note: The external script cannot contain the <script> tag! To use the external script, point to the .js file in the "src" attribute of the <script> tag:
<html> <head> <script src="xxx.js"></script> </head> <body> </body> </html>
Note: Remember to place the script exactly where you normally would write the script!
The JavaScript for creating an XMLHttpRequest object in your Ajax Application varies slightly for different browsers; Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); Internet Explorer 6.0+ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); Internet Explorer 5.5+ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
Most of the time a web developer cannot be sure about the type and version of browsers used by the target audience of the web application. In that case we may add some exception handling code to our JavaScript program to handle browser compatibility problems. We often use a series of trycatch statements to deal with such cross browser issues in JavaScript.
The complete JavaScript code dealing with these different browsers, for creating an XHR object is shown below.
<script type="text/javascript"> function ajaxFunction() { var xmlHttp; try{// Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) {// Internet Explorer 6.0+ try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e)
Dept. of CSE
39 Venjaramood
MACE,
{ try {//Internet Explorer 5.5+ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } } </script>
Code explained: First creates a variable xmlHttp to hold the XMLHttpRequest object. Then try to create the object with xmlHttp=new XMLHttpRequest(). This is for the Firefox, Opera, and Safari browsers. If that fails, try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP") which is for Internet Explorer 6.0+. If that also fails, try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") which is for Internet Explorer 5.5+. If none of these three methods work, the user has a very outdated browser, and he or she will get an alert stating that the browser doesn't support AJAX.
Dept. of CSE
40 Venjaramood
MACE,
Trivia: Msxml2.XMLHTTP vs. Microsoft.XMLHTTP If you look at different implementations of Ajax, youll notice that some use Microsoft.XMLHTTP and some use Msxml2.XMLHTTP when targeting IEs ActiveX control. So whats the difference? As it turns out, very little when written like that. While the Microsoft namespace is older than the Msxml2 namespace, written like this both statements will target MSXML 3.0 (the most widely distributed version of MSXML). The latest version of MSXML, though, is version 6.0 (released July 2006). Vista ships with version 6.0 installed and it is available for download for XP, Win2k, and Win2k3. To target the latest and most secure version of MSXML, you must use Msxml2.XMLHTTP.6.0 to create your XMLHttpRequest. Leaving the version number off on a system with 3.0 installed will always target MSXML 3.0 (even if 6.0 is installed).
Dept. of CSE
41 Venjaramood
MACE,
The onreadystatechange property stores the function that will process the response from a server. The following code defines an empty function and sets the onreadystatechange property at the same time:
xmlHttp.onreadystatechange=function() { // We are going to write some code here }
I have mentioned earlier (in section 6.2) about the readyState property of XHR object that holds the current status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed. The value of the readyState property can change several times with the current status of servers response even before the response is completely ready. So the value of the readyState must be checked to be equal to 4 to know whether the server has completed sending the response, before we can retrieve the response contents from responseText or responseXML property. So we are going to add an if statement to the onreadystatechange function to test if our response is complete (this means that we can get our data):
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { // Get the data from the server's response } }
When value of readyState is 4, the data sent back from the server can be retrieved directly in text format from the responseText property, or in XML format from the responseXML property.
<body> <script type="text/javascript"> function ajaxFunction() { var xmlHttp; try {// Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) {// Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); } </script> <form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" /> Time: <input type="text" name="time" /> </form>
Dept. of CSE 43 Venjaramood MACE,
</body> </html>
You may have noticed that this html code has embedded JavaScript that performs Ajax communication with the server to obtain the current server time by calling an asp server-side script "time.asp" and update a text field named time without refreshing the page. Also note that the Ajax function is triggered by an onkeyup event inside a text field named username. This means that the Ajax functions will be executed "behind the scenes" whenever the user types something in the username text field. The server-side script time.asp given below should be stored in the same directory as the html for this code to work properly. "time.asp" looks like this: <% response.expires=-1 response.write(time) %> Note: The expires property sets how long (in minutes) a page will be cached on a browser before it expires. If a user returns to the same page before it expires, the cached version is displayed. Response.Expires=-1 indicates that the page will never be cached.
9. Conclusion
9.1. When you should use Ajax
Dept. of CSE
44 Venjaramood
MACE,
In general, any UX (short for user experience, a more holistic approach than user interface or UI) in your application that does not involve navigation is a good candidate for Ajax. Common examples of these interactions are: a) A form that validates values with some server process b) A drop down list that loads values in response to another elements action c) Voting or rating input elements d) Multi-tab interfaces e) Any grid operations (such as sorting, selecting, editing, filtering, etc.)
Dept. of CSE
45 Venjaramood
MACE,
2. Format or structure of the webpage, which is almost always built in HTML or XHTML and is then reflected and made available to dynamic manipulation in the DOM 3. Style elements of the webpage: everything from fonts to picture placement are derived by reference to embedded or referenced CSS. 4. Functionality of the webpage, which is provided by a combination of: a. JavaScript on the client browser (Also called DHTML), b. Standard HTTP and XMLHttp or client-to-server communication, and c. Server-side scripting and/or programs using any suitable language preferred by the programmer to receive the client's specific requests and respond appropriately.
9.3.2. Response-time concerns Network latency or the interval between user request and server response needs to be considered carefully during Ajax development. Without clear feedback to the user, preloading of data and proper handling of the XMLHttpRequest object, users might experience delays in the interface of the web application, something which they might not expect or understand. Additionally, when an entire page is rendered there is a brief moment of re-adjustment for the eye when the content changes. The lack of this re-adjustment with smaller portions of the screen changing makes the latency more apparent. The use of visual feedback (such as throbbers) to alert the user of background activity and/or preloading of content and data are often suggested solutions to these latency issues. 9.3.3. Search engine optimization Websites that use Ajax to load data which should be indexed by search engines must be careful to provide equivalent Sitemaps data at a public, linked URL that the search engine can read, as search engines do not generally execute the JavaScript code required for Ajax functionality. This problem is not specific to Ajax, as the same issue occurs with sites that provide dynamic data as a full-page refresh in response to, say, a form submit (the general problem is sometimes called the hidden, or deep web). 9.3.4. Reliance on JavaScript Ajax relies on JavaScript, which is often implemented differently by different browsers or versions of a particular browser. Because of this, sites that use JavaScript may need to be tested in multiple browsers to check for compatibility issues. It's common to see JavaScript code written twice, one part for IE, another part for Mozilla compatibles, although this is less true with the release of IE7 and with the now-common use of JavaScript abstraction libraries like the Prototype JavaScript Framework or Jquery. Such libraries abstract browser-specific differences from the web developer. The level of IDE support for JavaScript used to be poor, although it is changing with more wide-spread use of tools like firebug, IE Developer Toolbar and Venkman.
Dept. of CSE
47 Venjaramood
MACE,
An issue also arises if the user has switched off JavaScript support in the browser, thus disabling the functionality built into the pages. 9.3.5. Web analytics Many web analytics solutions are based on the paradigm of a new page being loaded whenever new or updated content is displayed to the user, or to track a series of steps in a process such as a check-out. Since Ajax alters this process, care must be taken to account for how to instrument a page or a portion of a page so that it can be accurately tracked. Analytics systems which allow for the tracking of events other than a simple page view, such as the click of a button or link, are the ones most likely to be able to accommodate a site which heavily utilizes Ajax. 9.3.6. Accessibility Non-Ajax users would ideally continue to load and manipulate the whole page as a fall back, enabling the developers to preserve the experience of users in non-Ajax environments (including all relevant accessibility concerns) while giving those with capable browsers a much more responsive experience. For this reason it is advised to first develop a full application without Ajax, and implement Ajax enhancements as an addition only. The same counts for JavaScript in general, as this can be disabled in most browsers, thereby hindering user experience at Web sites that rely on these technologies.
9.4. Summing up
There is no doubt that Ajax is going to change the way we use the web. Ajax has started a new level of evolution in application models. The major challenges faced in developing Ajax applications are not
technical. Ajax opens a wider, richer range of possibilities web designers. In future we can expect to see more and more organizations following Googles lead in reaping the competitive advantages of Ajax. Its advisable to use Ajax only where it creates a considerable improvement in User experience.
Dept. of CSE
48 Venjaramood
MACE,
10. References
1. Ajax: A New Approach to Web Applications (by Jesse James
Garrett): http://www.adaptivepath.com/ideas/essays/archives/000385.php 2. Uniform Resource Identifier (URI): Generic Syntax. (The Internet Society-January 2005 ): http://www.ietf.org/rfc/rfc3986.txt 3. W3 Schools Ajax tutorial: http://www.w3schools.com/ajax/default.asp 4. W3 Schools XSLT tutorials: http://www.w3schools.com/xsl/default.asp 5. IBM developerWorks resources New to XML : http://www.ibm.com/developerworks/xml/newto 6. MSDN, Understanding and Solving Internet Explorer Leak Patterns, http://msdn.microsoft.com/library/default.asp? url=/library/enus/IETechCol/dnwebgen/ie_leak_patterns.asp 7. Telerik blogs The Ajax Papers (Part I, Part II & Part III): www.telerik.com/documents/AJAX%20Page/Ajax-Part1.pdf www.telerik.com/documents/AJAX%20Page/Ajax-Part2.pdf www.telerik.com/documents/AJAX%20Page/Ajax-Part3.pdf
Dept. of CSE
49 Venjaramood
MACE,