Sie sind auf Seite 1von 43

CHAPTER ONE INTRODUCTION

Ajax, which consists of XML, JavaScript technology, DHTML, and DOM, is an approach that helps developers transform clunky Web interfaces into interactive Ajax applications (McLaughlin, 2005). Consider the choice of applications that developers are writing such as desktop applications or Web applications. Desktop applications usually come on a CD or can be downloaded from a Web site and installed completely on any computer. They might use the Internet to download updates, but the code that runs these applications resides on the desktop. Web applications on the other hand run on a Web server somewhere and can access the application with a Web browser. More important than where the code for these applications runs, though, is how the applications behave and how they can be interacted with. Desktop applications are usually quite fast as they are running on a computer, therefore Internet connection speed is not an issue, and they have great graphical user interfaces which usually intera cts with the operating system. All and all they are incredibly dynamic. Desktop applications are extremely interactive these days, they can be clicked, pointed & typed with almost no waiting around (McLaughlin, 2005). On the other hand, Web applications are usually up to the second updated and they provide services which could not be got on a desktop, a really good example of this is eBay. 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 generate a new page. Again with the example of eBay, how frustrating when an auction is nearing its end and the current bidder is being outbid because of the length of time the page is taking to refresh before they can enter a new bid again, most times they have lost the item they were interested in (McLaughlin, 2006). Ajax attempts to bridge the gap between the
1

functionality and interactivity of a desktop application and the always -updated Web application. This technology uses dynamic user interfaces and fancier controls like that which are found on a desktop application, but now has become available on a Web application. AJAX is also a key component of Web 2.0 applications such as Flickr, now part of Yahoo!, 37signals' applications basecamp and backpack, as well as other Google applications such as Gmail and Orkut (OReilly, 2006). Another definition of AJAX coined by Jesse James Garrett on February 18, 2005 was that Ajax was not just one technology, but several, each flourishing in its own right, each coming together in powerful new ways. The reason for this definition is because AJAX incorporates several technologies including

y Standards-based presentation using XHTML and CSS y Dynamic display and interaction using the D ocument Object Model y Data interchange and manipulation using XML and XSLT y Asynchronous data retrieval using XMLHttpRequest y And JavaScript binding everything together

CHAPTER TWO

THEORITICAL BACKGROUND STUDY

2.1 HISTORY OF WEB SERVICES

Similar to almost every IT sector also in the part of Web services and programming the development and innovation of technologies in the last few decades was raised in a very significant way. As in 1989 Tim Berners Lee invented the Hypertext Markup Language, nobody knew what kind of rapid development it would lead to. In the first years HTML was only used for static websites and for layout purposes. But HTML is still, like nearly twenty years ago, also nowadays (today the XHTML 2.0 standard is common) hierarchically structured and assembled by so called tags. This is a very important aspect for the DOM Document Object Model, which will be evaluated later in detail. The more sites web designers and web programmers implemented, the more the demand for dynamic web sites increased. In 1998 first implementations of Dynamic HTML were published technically feasible with Java Script. These were the first fore-riders of the new AJAX framework, which generally only uses existing technologies. But not everyone w as affected with that hype, one of the problems was the Netscape Microsoft browser war. While Netscape invented the JavaScript object based language, Microsoft countered with its Jscript which had similar functionalities but for web programmers there were too many problems with compatibility. Also nowadays it is not easy to create Java Script applications compatible for every browser. While Microsoft uses the Active X support in its Internet Explorer, the Gecko browsers (Mozilla, Firefox, etc.) are not completely compatible to them. Later websites gained interactivity and dynamic actions through Java applets and Flash applications which all use the common browser -server request: a user opens a browser, sends a request to a server, the server handles the requ est and
3

gives it back to the browser where the user waits for the answer. With the help of AJAX a lot of these connections can be realized simultaneously while the user is working. In 2000 the establishment of XML allowed the describing of data. XML, which is a meta language, forms the basis of many Web services and allows to exchange 4 data in a standardized way. It also works with the use of tags, which can, in contrast to HTML, be self invented. For the last few years more end devices (mobiles, PDAs, etc.) have created a new challenge. Through these developments and evolutions the next step - building interactive Web applications was not very far away. Such interactive applications are the basis of the new generation of the Web - Web 2.0.

2.2 WEB 2.0

The latest generation of the World Wide Web is the so called Web 2.0. Through the development and the success of Web Services, information and several providers like Wikipedia.org or Google the kind of information exchange in the Web is changing and evolving. Interactive Web applications in which users

can be important interactors or can play parts within lead to eliminate the border to desktop applications. An example for these developments is the online photo shop and information service flickr. Users can upload their own photos and give them an XML-tag keyword they like. So others have the possibility to search for photos with these keywords. Table 1 shows the evolution of the Web. Another aspect of the new Web 2.0 generation is the trend away from p ersonal Websites to blogging information. A reason for the hype of Web 2.0 are that the broadband has become mainstream and ubiquitous, resulting in an increased usage of the Internet for even small tasks on different devices and so more

people go online for a variety of tasks and shopping-related activities. The trends go to

y A social phenomenon referring to an approach to creating and distributing

Web

content

itself,

characterized

by

open

communication,

decentralization of authority, freedom to share and re-use, and the market as a conversation.

y The transition of Websites from isolated information silos to sources of

content and functionality, thus becoming a computing platform serving Web applications to end users
y A more organized and categorized c ontent, with a far more developed

deep linking Web architecture Web 2.0 is a marketing term to differentiate new Web businesses from those of the dot com boom, which due to the bust now seem discredited
y The resurgence of excitement around the possibilities of innovative Web

applications and services that gained a lot of momentum around mid 2005.
2.3 JAVASCRIPT AND XML

Essentially taking each part of the acronym in isolation Asynchronous, means that when you a request is sent, the user must wait for a response to come back, but is free to do other things while they wait. The response probably does not come back immediate ly, so the developer can set up a function that will wait for it to be sent by the server, and react to it once it happens. The next stage is JavaScript. This code is the core code running Ajax applications. It is used to make a request to the server. Once the response is returned by the server, the developer will generally use some more JavaScript to modify the current pages document object model (DOM) in some way to show the user that the submission went through successfully. JavaScript is the scripting language of
5

the Web, it is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and is the most popular scripting language on the internet and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera etc. A big advantage for developers is the fact that it is easy to learn (W3Schools, 2006). JavaScript is a prototype based scripting language with a syntax loosely based on C. Like C, the language has no input or output constructs of its own. Whereas C relies on standard I/O libraries, a JavaScript engine relies on a host environment into which it is embedded. There are many such host environment applications, of which web technologies are the most well known examples. One major use of web based JavaScript is to write functions that are embedded on or included from HTML pages and interact with the Document Object Model of the page to perform tasks not possible in HTML alone. The final component in AJAX is XML. XML stands for Extensible Markup Language which is used as a way of describing data. An XML file can contain the data too, similar to that of a database. The primary purpose of XML is to facilitate the sharing of information across different systems, particular those connecte d to the internet. AJAX passes data to servers packaged up as snippets of XML code, so that it can be easily processed with JavaScript. This data can be anything which is needed, and as long as required. It is not a new technology as this is already how the web works, the only difference is that now these requests can be made from JavaScript. In short a file is requested and a page is received in response.

2.4 THE AJAX MODEL

Ajax is not a technology but rather a family of technologies that have been available for years, each flourishing in their own right and coming together in

significant new ways (Garrett, 2005). Ajax incorporates standards -based presentation using XHTML and CSS, the former is a stricter and cleaner version of HTML, which is used to build Web forms and identify fields for use in applications. The latter is CSS which stands for Cascading Style Sheets which define how to display HTML elements in a web application. These standards are W3C Recommendations which describe the communication p rotocols of HTML, XML and other building blocks of the Web (Garrett, 2005). Also incorporated in AJAX is dynamic display and interaction using the Document Object Model, data interchange and manipulation using XML and Extensible StyleSheet Language Transformations (XSLT), asynchronous data retrieval using XMLHttpRequest and JavaScript binding everything together which gives faster access, better support, and acceptance as a data structure in a Web application. The preferred way to communicate with the serve r is by sending data as XML but other methods can be used. Although XML provides two enormous advantages as a data representation language, as it is text based and is position independent. Unfortunately, XML is not well suited to data interchange as it carries a lot of baggage, and it does not match the data model of most programming languages. However there is another text notation that has all of the advantages of XML, but is much better suited to data interchange. That notation is JavaScript Object Notat ion (JSON). JSON is a lightweight computer data interchange format. It is a subset of the object literal notation of JavaScript but its use does not require Javascript. JSON's elegance and simplicity has resulted in its widespread use, especially as an alt ernative to XML in Ajax. One of the claimed advantages of JSON over XML as a data interchange format in this context is that it is much easier to write a JSON parser. JSON parses ten times quicker than XML, which is quite expensive to parse. In JavaScript itself, JSON can be parsed trivially using the eval() procedure. This was important for the acceptance of JSON within the Ajax programming community because of JavaScript's ubiquity among web browsers.
7

For that reason JSON is typically used in environments where the size of the data stream between the client and the server is of paramount importance hence its use by Google, Yahoo, etc, which serves millions of users and the source of the data can be explicitly trusted, and where the loss of fact access to c lient-side XSLT processing for data manipulation or UI generation is not a consideration. While JSON is often positioned against XML, it is not uncommon to see both JSON and XML used in the same application. For example, a client -side application which integrates Google Maps data with SOAP weather data requires support for both data formats. (JSON, The Fat Free Alternative To XML). Comparing XML and JSON on the attributes which are considered important, the first is how simplistic JSON is, it has a much smaller grammar and maps more directly onto the data structures used in modern programming languages therefore less coding is required compared to XML. It it also easier for humans to read and for machines to read and write. Secondly JSON is not extensible because it does not need to be. JSON is not a document mark-up language, so it is not necessary to define new tags or attributes to represent data in it. JSON has the same interoperability potential as XML and lastly is at least as open as XML, perhaps more so because it is not in the centre of corporate/political standardisation struggles (Kelly, 2005). Whatever is used XML or JSON, for developers to get the right look for an AJAX application, Cascading Style Sheets (CSS), a World Wide Web Consortium (W3C) standard is a crucial weapon in the AJAX developer's arsenal. CSS provides the mechanism for separating the style and design of an application from the content itself. Although CSS plays a prominent and important role in AJAX applications, it also tends to be one of the bigger stumbling blocks in building cross browser compatible applications since there are widely varying levels of support from different browser vendors (Johnson, 2006)

Therefore the real complexity in JavaScript programming results from th e incompatibility of Web browsers' support for varied technologies and standards. Building an application that runs on different browsers e.g. IE and Mozilla's Firefox is a difficult task to say the least. To that end, several AJAX JavaScript frameworks commercial and open source either generate JavaScript code based on server side logic or tag libraries, or provide a client side JavaScript library to facilitate cross browser AJAX development. Some of the more popular frameworks include AJAX.Net, Backbase, Bitkraft, Django, DOJO, DWR, MochiKit, Prototype, Rico, Sajax, Sarissa, and Script.aculo.us. The browser wars from a few years ago are still going on albeit on a much smaller scale. Therefore the effect on Ajax applications as regards the XMLHttpRequest fi nds itself one of the victims of this war. Consequently a few different things are necessary to get an XMLHttpRequest object going. The key is to support all browsers. No developer wants to write an application that works just on Internet Explorer or an application that works just on non -Microsoft browsers. Its a poor answer to write an application twice, therefore code should combine support for both Internet Explorer and non-Microsoft browsers in a multi browser way. Modern browsers offer users the ability to change their security levels, and to turn off JavaScript technology, disable any number of options in their browser. Therefore, developers need to han dle the problems associated with these changes without letting the application fall over. Writing robust code is a challenge for Ajax developers.

2.5 Web 2.0 and AJAX

There has been a lot of talk about the technology of Web 2.0, but only a little on the impact these technologies will have on user experience apart from Ajax of recent. The first "Real-World AJAX" event, held in New York City, featured 15 speakers in 11 sessions, including many of the world's most renowned AJAX
9

experts, and more than 400 delegates attended while more than 15,000 SYSCON.TV viewers tuned into the simulcast on March 13, 2006. At this seminar Jesse James Garrett (Adaptive Path publications) declared The biggest challenges in creating Ajax applications are not technical. The cor e Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities. The impact of Ajax for Web applications covers a wide range of issues, business strategy, technology, design, team structure and processes are all potentially affected by the move to Ajax. (Garrett, 2005) This middle of the road approach as opposed to screen based approaches which mimic the sophistication of desktop applications, with Java, Flash or a similar technology or page based approaches which force developers to deal with the load-reload effect of normal web pages. Resulting in users who enter and manipulate information in page based applications sitting through a page refresh in order for their changes to take place. The Amazon.com checkout sequence, Google search, and the eBay selling sequence are common examples of the page based approach. While both approaches have proven successful, each has drawbacks. Ajax on the other hand marries the benefits of both screen and paged based approaches by allowing more sophisticated functionality using easier to implement web standards. Ajax is a solid alterna tive for new interface development and experts have already affirmed the viability of the web as a standalone software development platform. Its popularity is certainly helped with large companies like Google creating amazing applications using the Ajax technology eg Google Maps, Google Gmail, and Google Suggest and another reason is the continuing adoption of standards compliant browsers that support Ajax technology, Firefox, Safari, Opera, and Internet Explorer 6 (Porter, 2005). Most notably Firefox, for their support of Ajax software, eg ajaxWrite,
10

ajaxTunes which are all small rich web based applications which run on a computer. These programs launch in 3-4 seconds and have all the interactivety of Writely or Microsoft Office applications. Ajax13 1 has just 6-8 servers and serves millions of people with their service from servers web based applications. Their goal is to show all core applications from the Internet. They believe that consumers dont need to know anything about version compatibility with their existing computer or operating system.

11

CHAPTER THREE DISCUSSION

3.1 DEFINITION

Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data are usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous. Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

3.2 TECHNOLOGIES

The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that the following technologies are required:

12

y y

HTML or XHTML and CSS for presentation the Document Object Model for dynamic display of and interaction with data

XML and XSLT for the interchange, and manipulation and display, of data, respectively

y y

the XMLHttpRequest object for asynchronous communication JavaScript to bring these technologies together

Since then, however, there have been a number of developments in the technologies used in an Ajax application, and the definition of the term Ajax. In particular, it has been noted that:
y

JavaScript is not the only client-side scripting language that can be used for implementing an Ajax application. Other languages such as VBScript are also capable of the required functionali ty. However JavaScript is the most popular language for Ajax programming due to its inclusion in and compatibility with the majority of modern web browsers.

XML is not required for data interchange and therefore XSLT is not required for the manipulation of data. JavaScript Object Notation (JSON) is often used as an alternative format for data interchange, although other formats such as preformatted HTML or plain text can also be used. Classic Ajax involves writing ad hoc JavaScript on the client. A simpler if cruder alternative is to use standard JavaScript libraries that can partially update a page, such as ASP.Net's UpdatePanel. Tools such as Echo2 and ZK enable fine grained control of a page from the server, using only standard JavaScript libraries.

13

3.3 WHY USE AJAX?

Mainly AJAX is used to build a fast, dynamic website, and also to save resources. For improving sharing of resources, it is better to use the power of all the client computers rather than just a unique server and network. Ajax allows performing processing on client computer (in JavaScript) with data taken from the server. The processing of web page formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network. But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc. For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.

3.4 AJAX AS A COMBINATION OF TECHNOLOGIES

The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page: HTML and CSS for presenting. JavaScript for local processing, and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server The XMLHttpRequest object is used to read or send data on the server asynchronously

Optionally: DOM Parser may be used. PHP or another scripting language may be used on the server. XML and XSLT to process the data if returned in XML form

14

3.5 HOW AJAX WORKS?

Ajax uses a programming model with display and events. These events are user actions; they call functions associated to elements of the web page. Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server. To get data on the server, XMLHttpRequest provides two methods:
y Open: create a connection. y Send: send a request to the server.

Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
y responseXml for an XML file or y responseText for a plain text.

Take note that a new XMLHttpRequest object has to be created for each new file to load. We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the ready State attribute of XMLHttpRequest. States of readyState follow (only the last one is really useful): 0: not initialized. 1: connection established. 2: request received. 3: answer in process. 4: finished. Before discussing how Ajax works, you should know how the old technologies work. Why should you know how the old technologies work? The answer is simply to observe the difference between the old technologies and Ajax. The action is sent to the server by requesting an HTTP trigger and you, the internet user, wait to the server to respond. It is also not that simple. The server will do
15

many jobs in each request. After doing some processing stuff the server will respond to the client (see figure2).

Figure 2: AJAX versus the classic Web Application Model (Garrett, 2005)

This way is very technical but do you ask yourself this question: What you will do when the server does its jobs? The answer is nothing but waiting for the jobs to be done by the server. This is clearly a problem. It is wasting time and money. on the other hand, Ajax will eliminate the number of interactions with the server by asking the server to do some specific job(s). How Ajax does that? This is done by putting Ajax Engine in the middle between the client and the server. Ajax engine will make the application is less responsive. Furthermore, after knowing that there is something called Ajax engine but you where it is or
16

how to get it. Do not worry, the user does not have to download this engine or buy it. It is simply when the user tries to load the webpage, the Ajax engine will be loaded instead. This engine is written in JavaScript. Rendering the visual interface and interaction with the server is not a users responsibilities it is an Ajax engines responsibilities. This whole processes take place asynchronously. It is independent of communication with the server. So, if you want to re -load or update the web page, then you do not have to start from an empty webpage. So, the internets user will interact with Ajax engine instead of interacting with the server.

3.6 THE ANATOMY OF AN AJAX INTERACTION

Now that we have discussed what Ajax is and what some higher-level issues are, let's put all the pieces together and look at an Ajax-enabled Java application. Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.

17

Figure 1: An Ajax Interaction Provides Validation Logic The following items represent the setups of an Ajax interaction as they appear in Figure 1. 1. A client event occurs. 2. An XMLHttpRequest object is created and configured. 3. The XMLHttpRequest object makes a call. 4. The request is processed by the ValidateServlet. 5. The ValidateServlet returns an XML document containing the result. 6. The XMLHttpRequest object calls the callback() function and processes the result. 7. The HTML DOM is updated. Now let's look at each step of the Ajax interaction in more detail.

18

3.6.1 A Client Event Occurs.

JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component. <input type="text" size="20" id="userid" name="id" onkeyup="validate();">

This form element will call the validate() function each time the user presses a key in the form field.

3.6.2 A XMLHttpRequest object is created and configured.

An XMLHttpRequest object is created and configured. var req;

function validate() {

19

var idField = document.getElementById("userid"); var url = "validate?id=" + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", url, true); req.onreadystatechange = callback; req.send(null); }

The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function fo r this interaction is set with the statement req.onreadystatechange = callback; . See section 6 for more details.

20

3.6.3 The XMLHttpRequest object makes a call.

When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter. Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some bro wsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server -side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement: req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send("id=" + encodeURIComponent(idTextField.value));

When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.

21

3.5.4 The request is processed by the ValidateServlet.

A servlet mapped to the URI "validate" checks whether the user ID is in the user database. A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken. public class ValidateServlet extends HttpServlet {

private ServletContext context; private HashMap users = new HashMap();

public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); users.put("greg","account data"); users.put("duke","account data"); }

public void doGet(HttpServletRequest request, HttpServletResponse response)

22

throws IOException, ServletException {

String targetId = request.getParameter("id");

if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<message>valid</message>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<message>invalid</message>"); } } }

In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.

23

3.6.5 The ValidateServlet returns an XML document containing the results.

The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the response. response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<message>invalid</message>");

The developer must be aware of two things. First, the Content-Type must be set to text/xml. Second, the Cache-Control must be set to no-cache. The XMLHttpRequest object will process only requests that are of the Content-Type of only text/xml, and setting Cache-Control to no- cache will keep browsers from locally caching responses for cases in which duplicate requests for the same URL (including URL parameters) may return different responses.

3.5.6 The XMLHttpRequest object calls the callback() function and processes the result.

The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us

24

assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction. function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } }

Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded. Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM
25

APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet. <message> valid </message>

This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user: function parseMessage() { var message = req.responseXML.getElementsByTagName("message")[0]; setMessage(message.childNodes[0].nodeValue); }

The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.

26

3.6.7 The HTML DOM is updated.

JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById("userIdMessage"), where

"userIdMessage" is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements. One common means to change the body content of an element is to set the innerHTML property on the element as in the following example. <script type="text/javascript"> ... function setMessage(message) { var mdiv = document.getElementById("userIdMessage"); if (message == "invalid") { mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</ div>"; } else { mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</ div>"; } } </script>

27

<body> <div id="userIdMessage"></div> </body>

The portions of the HTML page that were affected are re -rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well. Ajax applications such as Google Maps use this technique of adding image elements using Ajax calls to dynamically build maps. The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hard coding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit. Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the f ollowing example. <script type="text/javascript"> ... function setMessage(message) {

28

var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "invalid") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple replace it otherwise // append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } </script>

29

<body> <div id="userIdMessage"></div> </body>

The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applicatio ns.

3.7 ADVANTAGES: Bandwidth utilization: In many cases, related pages on a website consist of

much content that is common between them. Using traditional methods, that content would have to be reloaded on every request. However, using Ajax, a web application can request only the content that needs to be updated, thus drastically reducing bandwidth usage and load time.
User interface: The use of asynchronous requests allows the client's Web

browser UI to be more interactive and to respond quickly to inputs, and sections of pages can also be reloaded individually. Users may perceive the application to be faster or more responsive, even if the application has not changed on the server side.
More efficient: The use of Ajax can reduce connections to the server, since

scripts and style sheets only have to be requested once. State can be maintained throughout a Web site. JavaScript va riables will persist because the main container page need not be reloaded.

30

3.8 CHALLENGES FACED WHEN USING AJAX


y

Complexity:

Server-side developers will need to understand that

presentation logic will be required in the HTML client pages as well as in the server-side logic to generate the XML content needed by the client HTML pages. HTML page developers need to have a basic und erstanding of JavaScript technology to create new Ajax functionality. Other options such as Project jMaki and Project Dynamic Faces provide a way for Java developers to better use Ajax functionality without requiring deep knowledge of JavaScript technology.
y

Standardization of the XMLHttpRequest object: The XMLHttpRequest

object is not yet part of the JavaScript technology specificati on, which means that the behavior may vary depending on the client. It's best to use libraries such as Dojo, which provides fallback solutions for making Ajax interactions transparently even on older bro wsers that do not support the XMLHttpRequest Object:.
y

JavaScript technology implementations: Ajax interactions depend heavily

on JavaScript technology, which has subtle differences depending on the client. See QuirksMode.org for more details on browser-specific differences. Consider using a library such as Dojo, which addresses many of the differences.
y

Debugging: Ajax applications are also difficult to debug because the

processing logic is embedded both in the client and on the server. Browser add-ons such as Mozilla Firebug have emerged to make debuging easier. Frameworks such as the Google Web Toolkit have emerged to allow for client and server round-trip debugging.
31

Securing resources and protecting your data: You can view client-side

JavaScript technology simply by selectin g View Source from an Ajaxenabled HTML page. A poorly designed Ajax-based application could open itself up to hackers or plagiarism. When providing Ajax services, you should take care to make sure that those services are made available only to those intended. See Restricting Access to Your Ajax Services for more information on protecting your services.
3.9 SOME USES FOR AJAX INTERACTIONS ARE THE FOLLOWING:
y

Real-time form data validation: Form data such as user IDs, serial

numbers, postal codes, or even special coupon codes that require server -side validation can be validated in a form before the user submits a form. See Real time Form Validation for details.
y

Auto completion: A specific portion of form data such as an email address,

name, or city name may be auto comp leted as the user types.
y

Load on demand: Based on a client event, an HTML page can fetch more

data in the background, allowing the browser to load pages more quickly.
y

Sophisticated user interface controls and effects: Controls such as trees,

menus, data tables, rich text editors, calendars, and progress bars allow for better user interaction and interaction with HTML pages, generally without requiring the user to reload the page.
y

Refreshing data and server push: HTML pages may poll data from a

server for up-to-date data such as scores, stock quotes, weather, or application-specific data. A client may use Ajax techniques to get a set of current data without reloading a full page. Polling is not the most efficient means of ensuring that data on a page is th e most current. Emerging techniques such as Comet are being developed to provide true server -side
32

push over HTTP by keeping a persistent connection between the client and server. See this blog entry on Comet using Grizzly for more on the development of server push with Java technology.
y

Partial submit: An HTML page can submit form data as needed without

requiring a full page refresh.


y

Mashups: An HTML page can obtain data using a server -side proxy or by

including an external script to mix external data with your application's or your service's data. For example, you can mix content or data from a th irdparty application such as Google Maps with your own application.
y

Page as an application: Ajax techniques can be made to create single -page

applications that look and feel much like a desktop application. See the article on the use of Ajax and portlets for more on how you can use portlet applications today.

33

CHAPTER FOUR REAL WORLD AJAX APPLICATIONS


y

Google Live Search

Auto Complete

34

Chat Application

Dragging And Dropping

35

Instant Login Feedback

Google Earth : is a virtual globe, map and geographical information program that was originally called EarthViewer 3D, and was created byKeyhole, Inc, a company acquired by Google in 2004. It maps the Earth by the superimposition of images obtained from satellite

imagery,aerial photography and GIS 3D globe

36

Google Enabled Yahoo!

37

CHAPTER FIVE 5.1 FUTURE:

Big applications of Ajax showed that it is not just a technical issues but it is a real world application. As the seminar demonstrates earlier, Ajax has the ability to grow. Ajax applications face some non-technical difficulties. For instance, the programmers and the developers are not quali fied yet to implement this approach. However, big companies like Microsoft, Sun Microsystems Inc and TIBCO Software Inc want to use Ajax in their applications . This step will make Ajax is very popular. Microsoft wants to develop smart client strategy by implementing Ajax . Microsoft Atlas is an Ajax based programming framework.

5.2 DRAWBACKS: y The ease of use of Ajax-powered interfaces often dramatically increases

the number of user-generated requests to web servers and their back -ends (databases, or other). This can lead to slower response times and additional hardware needs to support Ajax-powered interfaces.
y Pages dynamically created using successive Ajax requests do not

automatically register themselves with the browser's history engine, so clicking the browser's "back" button may not return the user to an earlier state of the Ajax-enabled page, but may instead return them to the last full page visited before it.

y Because most web crawlers do not execute JavaScript code, publicly

indexable web applications should provide an alternative means of

38

accessing the content that would normally be retrieved with Ajax, to allow search engines to index it.
y Any user whose browser does not support Ajax or JavaScript, or simply

has JavaScript disabled, will not be able to use its functionality. Similarly, devices such as mobile phones, PDAs, and screen readers may not have support for JavaScript or the XMLHttpRequest object.
y If JavaScript is not activated, Ajax can't works. The user must be asked to

set JavaScript from within options of the browser, with the "noscript" tag.
y Since data to display are loaded dynamically, they are not part of the

page, and the Keywords inside are not viewed by search engines.
y The asynchronous mode may change the page with delays (when the

processing on the Server takes some times), this may be disturbing. The back button may be deactivated. This may be overcome.

5.3 SUMMARY

Web developers and programmers have to decide if AJAX will really be a Common used standard in the next decade. Critics say there is nothing new With AJAX, its only a marketing term for old dynamic HTML combined with JavaScript. Through the common use of broadband internet connections the more server connections in the background wont be that slow, other criticism is security and compatibility aspects because of Microsofts Active X standards. It is not possible to use AJAX in every problem or with every Website but it is a useful way to gain interactivity and it is easy to learn and extend. Not everything can be done with AJAX but it is a new challenge and a step further for disappearing the border between desktop applications and Web applications and services. With the help of frameworks AJAX is a very powerful technique,
39

No matter if its only a term for well established technologies.

5.4 CONCLUSION

We have seen that Ajax interactions can solve many problems. Java technology provides a good base to develop and deploy Ajax -based applications with APIs for tying in HTTP processing, databases, web services, XML processing, and business objects. With a better understanding of this interaction model, today's applications can become more interactive, providing the end user with a better experience. Using Ajax requires that you use the latest browser versions that support the XMLHttpRequest object needed for Ajax interactions. Using Ajax also requires a great deal of client-side JavaScript technology and CSS. As an application architect or developer, you will need to weigh the needs of having a rich application against browser support, architecture complexity , and developer training. As the Ajax programming model evolves, existing technologies and frameworks will make this transition easier.

40

5.5 ABBREVIATIONS AND CONCEPTS Ajax - Asynchronous Javascript And Xml, a technique used in web application

development.
ASP - Active Server Pages, a web-scripting interface by Microsoft. ASP.NET -

is a web application framework developed and marketed allow programmers to build dynamic web sites, web

by Microsoft to

applications and web services.


Backbase

- AJAX framework using HTML, Javascript and CSS. Backbase

used the term Rich Internet Applications to classify its software.


CSS Cascading Style Sheet is a style sheet language used to describe

the presentation semantics (the look and formatting) of a document written in a markup language.
DOM Document Object Model, a way to refer to XML or (X)HTML

elements as objects.
DHTML - Dynamic hypertext markup language, is an umbrella term for a

collection of technologies used together to create interactive and animated web sites.
DOJO Toolkit - is an open source modular JavaScript library (or more

specifically JavaScript toolkit) designed to ease the rapid development of cross platform, JavaScript/Ajax-based applications and web sites.
DWR - a Java open source library. JSON Javascript Object Notation. LAMP - (software bundle), a platform consisting of Linux, Apache, MySQL

and Perl/PHP/Python
41

MochiK - it is a light-weight Javascript library written and maintained by Bob

Ippolito.
PDA - Personal digital assistant, an electronic device which can include some

of the functions of a computer, a cellphone, a music player, and a camera Tag (metadata) - a keyword or term associated with or assigned to a piece of information.
PHP - Hypertext Preprocessor is a widely used, general-purpose scripting

language that was originally designed for web development to produce dynamic web pages.
Rico - a JavaScript library for creating web applications. Sajax(Simple Ajax Toolkit) -

is an open source tool designed to

help websites using the Ajax framework (also known as XMLHttpRequest).


W3C

The World

Wide

Web

Consortium (W3C)

is

the

main international standards organization for the World Wide Web (abbreviated WWW or W3).
XHTML - Extensive Hypertext Markup Language XML Extensive Markup Language. is a set of rules for encoding documents

in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C.
XMLHttpRequest (XHR)

is an API available in web browser scripting

languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script.

42

XSLT

Extensible

StyleSheet

Language

Transformations.

is

a declarative, XML-based language used for the transformation of XML documents.

5.6 REFERENCES

1. Christian Wenz. Ajax. Entwicklerpress (2006), 2006. 2. Forschung Urstein. Tourimus Info Gate (TEC/TIGS). http://www. tourimus-info-gate.at, 2006. 3. Gerhild Maier. Ajax von A bis X. http://krottmaier.cgv.tugraz.at/docs/ seminar/sem2005_ajax.pdf, 2006. 4. Google. Google Gmail. http://gmail.google.com, 2005. 5. Google. Google Suggest. http://www.google.com/webhp?hl=de, 2006. 6. Google. Google Maps. http://maps.google.com, 2006. 7. Microsoft. ATLAS. http://www.microsoft.com/germany/msdn/library/web/ AJAXUndASPNET.mspx?mfr=true, 2006. 8. W3C Community. DOM 3.0. http://www.w3.org/TR/2004/ NOTE-DOM-Level-3-XPath-20040226/, 2006. 9. Paul Miller. Web 2.0: Building the New Library. http://www.ariadne.ac.uk/ issue45/miller/, 2006. 10. Sarissa. Javascript Library. http://swik.net/Sarissa/, 2006. 11. www.wikepedia.com . 12. Simple Ajax Toolkit. SAJAX. http://www.modernmethod.com/sajax/, 2006. 13. The Web Word Processor. Writely. http://www2.writely.com/info/ WritelyOverflowWelcome.htm, 2006. 14. Tim OReilly. What is Web 2.0 ? http://www.oreillynet.com/pub/a/oreilly/ tim/news/2005/09/30/what-is-web-20.html (23.05.2006), 2006.

43

Das könnte Ihnen auch gefallen