Your SlideShare is downloading. ×
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. ITU Project: AJAX – Enhancing interactive web-based applications Peter Madsen & Allan Thræn AJAX Enhancing interactive web-based applications ITU, Copenhagen, Denmark 12 weeks project, 7.5 ECTS - Hand-in April 28th 2006 - Supervisor: Yvonne Dittrich Page 1 / 51 April 2006
  • 2. ITU Project: AJAX – Enhancing interactive web-based applications Table of Contents 1 Introduction...................................................................................................................... 4 1.1 The shift from information-centric to functionality-centric web.............................. 4 1.2 Rich Internet Applications (RIAs) ............................................................................ 5 1.3 The scope of this report............................................................................................. 6 2. The challenges of developing web applications and RIAs ............................................. 7 2.1 The web browser as an application host ................................................................... 7 2.2 The statelessness of web-applications ...................................................................... 7 2.3 The HTTP request/response model........................................................................... 8 2.4 Developer tools and skills......................................................................................... 8 2.5 Separation of concerns.............................................................................................. 9 2.6 Lack of rich user interface controls .......................................................................... 9 2.7 Challenges summarized .......................................................................................... 10 3 The AJAX concept......................................................................................................... 11 3.1 The term “AJAX” ................................................................................................... 11 3.2 What is AJAX all about? ........................................................................................ 11 3.3 AJAX vs. classic web applications ......................................................................... 12 3.4 Typical Uses of AJAX ............................................................................................ 14 3.5 Basic Example ........................................................................................................ 14 3.6 AJAX Frameworks ................................................................................................. 16 3.7 Advanced AJAX – Design Patterns........................................................................ 17 4 CASE: Search & Result page ........................................................................................ 18 4.1 Website Search........................................................................................................ 18 4.2 Interactivity in a search & result page .................................................................... 18 4.3 Our Implementation ................................................................................................ 19 4.4 Choosing an AJAX Framework.............................................................................. 20 4.5 Architecture overview............................................................................................. 21 4.6 Classic Search Web Application............................................................................. 22 4.7 AJAX Search Web Application .............................................................................. 22 4.7.1 Search Box ....................................................................................................... 23 4.7.2 Search Button................................................................................................... 24 4.7.3 Narrow search functionality............................................................................. 24 4.7.4 Results listing and pagination .......................................................................... 25 4.8 Summary ................................................................................................................. 25 5. AJAX, the good, the bad and the ugly .......................................................................... 26 5.1 The browser as an application host......................................................................... 26 5.2 The statelessness of web applications..................................................................... 27 5.3 The HTTP request/response model......................................................................... 28 5.4 Developer tools and skills....................................................................................... 29 5.5 Separation of concerns............................................................................................ 31 5.6 Lack of rich user interface controls ........................................................................ 32 6 Future works and limitations ......................................................................................... 33 Page 2 / 51 April 2006
  • 3. ITU Project: AJAX – Enhancing interactive web-based applications 7 Conclusion ..................................................................................................................... 34 8 Literature........................................................................................................................ 35 8.1 Regular Sources ...................................................................................................... 35 8.2 Sources on the Web ................................................................................................ 36 8.3 Web Applications.................................................................................................... 36 9 Glossary ......................................................................................................................... 38 10 Appendix: Source code for prototype .......................................................................... 39 10.1 SearchEngine.cs .................................................................................................... 39 10.2 NoAjaxSearch.aspx............................................................................................... 43 10.3 NoAjaxSearch.cs................................................................................................... 45 10.4 AjaxSearch.aspx.................................................................................................... 46 10.5 AjaxSearch.cs........................................................................................................ 49 Page 3 / 51 April 2006
  • 4. ITU Project: AJAX – Enhancing interactive web-based applications 1 Introduction As increasingly complex applications are brought into the Internet domain, there is a need to support sophisticated user interface designs and a more responsive communication flow [11]. The de-facto standard for interaction on the Internet is the web browser, which was originally developed as tool for reading documents linked together by hyperlinks. This heritage as a reader makes it a challenge to develop web browser hosted applications, which approach desktop applications in terms of user interface functionality and communication [5]. Lately there has been a lot of hype on the Internet about AJAX (an acronym for Asynchronous Javascript And XML) as an architecture for creating browser based applications, and a number of sophisticated applications based on AJAX have emerged from e.g. Google, Microsoft and others. In this paper we will investigate the virtues of AJAX as a method for developing browser based applications with rich interfaces and responsive communication. We will examine the implications of using AJAX, both from a user interaction perspective and a developer perspective. 1.1 The shift from information-centric to functionality-centric web Since the emergence of the World Wide Web in the mid 1990s its two most popular applications: the web browser and email have become almost synonymous with the Internet. While more sophisticated email clients have emerged in these past 10 years, the basic functionality of email protocols and applications have remained virtually unchanged. The browser and the specifications, on which it relies on the other hand, have been constantly changing, and support has been added for a much new functionality through the advent of updated Hyper Text Markup Language (HTML) specifications, Cascading Style Sheets (CSS), Dynamic HTML (DHTML) that relies on manipulation of the Document Object Model (DOM) and client side scripting (mostly Javascript). The first websites developed for browsers were nothing more than static pages, but soon the emergence of various technologies on the web server led to web sites based on dynamic page rendering through the use of CGI, Perl, PHP, ASP, Javabeans and other server side technologies. The shift from static to dynamic web pages has enabled more easily updatable websites, presenting more interesting and up-to-date information, but still the focus and aim of such web sites is primarily to be information providers. Now the focus of web sites is shifting once again from providers of information to providers of functionality i.e. full blown applications [3] [12]. Many such web applications at different levels of sophistication already exist, e.g. web stores, booking systems and public service portals etc. The technology on the server side for creating web applications has evolved from simple loosely typed scripting languages with a very basic support for modern object oriented Page 4 / 51 April 2006
  • 5. ITU Project: AJAX – Enhancing interactive web-based applications features, to mature full blown object oriented languages and frameworks that enable very large maintainable and scaleable n-tier applications. While server side technology has evolved into professional software tools supporting feature rich languages and modern architectural concepts of layered applications, the client side, i.e. the browser, is quite a different matter. Although CSS has enabled a better separation of content/formatting and DHTML and Javascript have facilitated some client side processing, these tools can be seen as technology “islands”, i.e. they have evolved as independent application domains and must be carefully “glued together” in order to perform as one coherent application. Several reasons exist for this incoherent programming model. The first browsers were not application tools at all, but merely render engines, that were driven by specification languages (HTML and later CSS), and the design of modern browsers is still mainly driven by this basic concept. Furthermore all new browser technology has been built on top of previous versions, since backward compatibility has been a major concern in the attempt not to break the code of existing websites. For this reason a complete rewrite and paradigm shift in the role of the browser has not been possible, if at all wanted by The World Wide Web Consortium (W3C), who governs the specifications of e.g. HTML, DHTML and CSS. 1.2 Rich Internet Applications (RIAs) As the focus is shifting from information to functionality, the users’ expectations of browser applications are also increasing. There is a need to support advanced multimedia types such as sound and video and a wish for browser applications to behave more like familiar desktop applications. The browser support for multimedia is exclusively supported through plug-ins (such as Macromedia Flash, Apple QuickTime etc.) that in essence are black-box objects hosted by the browser. [11]. The behavioral aspect of browser applications mimicking desktop applications is lately being enabled by a new technology: AJAX that is based on the support of features already built in to most modern browsers. While the concept of using Javascript to perform silent, asynchronous communication with the server is not entirely new, no tools have previously existed to aid the complicated process of designing such communication and behavior, and the concept had not been given a widely accepted name previously. As stated AJAX in itself is an architectural concept and not a tool as such, and therefore several implementations exist in the form of frameworks or libraries. These implementations are being developed both by software vendors such as Microsoft and as open source projects. Like multimedia support RIAs can also be created by various tools that generate embedded browser objects: Java applets, Macromedia Flash, Macromedia Shockwave, Microsoft ActiveX components etc. In a controlled environment where the capabilities and requirements of the target browsers are known, the embedded object application can be a fitting alternative to the AJAX approach. Other reasons for choosing third-party tools for compiling embedded objects to create RIAs could be security aspects (e.g. built- in support for encryption etc.), the usage of special features only supported by the tool and perhaps to leverage programming expertise in a certain tool. Page 5 / 51 April 2006
  • 6. ITU Project: AJAX – Enhancing interactive web-based applications For the use of AJAX speaks that it doesn’t require any extra plug-ins to be installed on the client, it is cross-browser and cross-platform compatible, at least for the subset of browsers that support the Javascript and XML features required for the chosen AJAX implementation. Furthermore AJAX is a “safe” technology in that it obeys the security settings of the user’s browser, while for instance Microsoft ActiveX components once installed have all the privileges of the current Windows user account, i.e. they basically rely on user trust to protect against malicious code running on the client. 1.3 The scope of this report In this report we choose to investigate AJAX for developing RIAs because it has the potential to reach the biggest target audience, since it is supported by most modern browsers “out-of-the-box” and because it promises possible adoption by a very large base of web application developers, since it relies on a familiar group of technologies. Our aim is to discover whether or not AJAX can fulfill the promise of delivering browser hosted applications, which provide better interfaces and communication to the user. We will base our report on studies of relevant literature, on-line sources, real world AJAX implementations and a case study of implementing a typical website Search & Result application. In our case study we will implement a standard form based version and an AJAX based version. In the comparisons we will focus mostly on the user interface/communication aspect, but we will also look at AJAX from an architectural, development and maintainability perspective. Page 6 / 51 April 2006
  • 7. ITU Project: AJAX – Enhancing interactive web-based applications 2. The challenges of developing web applications and RIAs Developing Industrial strength applications that are functional, user-friendly, stable, error-resistant, well performing and scalable is a challenge on any platform, but even more so if the application is to be deployed in a web browser/web server environment. In this chapter we will identify important challenges in developing web applications and in particular Rich Internet Applications. Later in this paper we will discuss whether or not AJAX can address some of these challenges and how, based on the findings form our prototype construction. 2.1 The web browser as an application host As the name “web browser” implies, a web browser’s primary function is to enable the browsing of documents on the World Wide Web, which is done by allowing the user to follow the hyperlinks on a web page that interconnects it to other pages on the Internet to form a “web” [5]. This basic underlying principle is expressed in the browser’s interface through the navigational commands available to the user such as the “back/forward” buttons, the “stop/cancel” button and the “refresh” button. These commands enable the user to effectively retransmit any request previously made or to cancel a pending request. While it makes a great deal of sense in an application meant for browsing information to be able to revisit documents previously viewed, it can play havoc with a transactional system meant for mission critical data entry to retransmit (or cancel) requests, if the system is not carefully guarded against re-transmitted and aborted transactions. 2.2 The statelessness of web-applications The HTTP protocol is stateless as are web server applications by default i.e. the communication employs Representational State Transfer (REST) architectural style [6]. Since many applications depend on statefull information to be persisted between transactions (e.g. whether or not a user in authenticated), state has to be persisted by the application itself, typically on both the client and the server. Different schemes exist for persisting state - on the client side it is usually handled by cookies, query parameters or hidden form fields. On the server side it is typically implemented by a session object [10] (which relies on the client to provide a token that is used as a key to store and retrieve the session object that holds statefull information). The complexity arises from the fact, that the server regards any transaction as a stateless and independent transaction, and therefore the developer has to decide what, when and how to persist and retrieve statefull information, which is not trivial in a complicated application. The persistence and restoration of statefull information also needs to address the issue of re-transmitted or aborted transactions. Page 7 / 51 April 2006
  • 8. ITU Project: AJAX – Enhancing interactive web-based applications 2.3 The HTTP request/response model One of the reasons why a desktop application often seems to have a more responsive and intuitive interface, is that user input can result in updates to the user interface, which only affects part(s) of the screen, so that a complete redraw is not necessary. A desktop application is tightly coupled to its user interface and has complete synchronization between the parts of its model and views without the need to (explicitly) store and retrieve state between events. A web application that is based on the HTTP request/response model will by default transmit all input data (as request parameters or form fields) in a request and receive complete web pages in the response by the web server [6]. As a result large amounts of data needs to be pushed to and from the user’s web browser resulting poor response times, especially if the page contain multiple images or other media, since each of these elements will result in a discrete request operation to fetch data on the web server (or web servers, since the parts could be fetched from a number of different domains). Of course the web browser will attempt to speed the process of fetching media elements by using a local cache, but even so the browser still needs to redraw the entire screen. This process that can be time consuming for a complicated page and will seem clumsy to the user, since a lengthy complete redraw of the screen may happen even if very little actually changed on the screen. A consequence of this architecture is that in a traditional web application almost all processing is done at the server [5], which of course adds to the un-responsive feel of the client side application. A well constructed desktop application will feel more responsive, because it allows the user to interact with parts of the interface even though other parts are being updated, a browser based web application, on the other hand, will not allow simultaneous actions to the same document to take place between a request has been issued and until the response has been received. This matter is of course aggravated by combinations of limited bandwidth, large data transfers and server bottlenecks. 2.4 Developer tools and skills For many years the tendency in application development was to provide developers with development suites and frameworks aimed at addressing all aspects of application development from graphical user interface design and construction, application event handling, database design and access layering and transaction handling, often called 4th Generation Languages (4GLs). Very large applications have been developed in e.g. IBM’s CICS, Oracle’s development suites and others. These systems are platforms, which typically include not only development suites, but also complete run-time systems (TP monitors and database servers) [4]. Also the diversity of programming languages was far less; it basically boiled more or less down to COBOL for business applications and C/C++ for scientific applications. What all this meant for the developer was that he was able to master all the necessary skills to construct functional and scalable applications learning a finite and coherent set of tools. In contrast an almost infinite number of tools exist to construct web applications. While it is not necessary to learn them all, a good web application developer has to know about (and master in various degrees): Page 8 / 51 April 2006
  • 9. ITU Project: AJAX – Enhancing interactive web-based applications • HTML • CSS • Javascript • DHTML and the DOM • Hyper Text Transfer Protocol (HTTP) • eXtensible Markup Language (XML) • eXtensible Stylesheet Language Transformations (XSLT) • Structured Query Language (SQL) • graphical user interface design • database design • server side frameworks and languages (e.g. PHP, ASP, JSP,.Net, Javabeans etc.) • Macromedia Flash (some environments) • Java applet programming (some environments) While some of these skills are often handled by different specialized developers and designers in larger organizations, a basic knowledge at least of the technologies and how they fit together will enable better applications. This is especially true on the client side, since there is little to explicitly tie the various parts (HTML, CSS, Javascript, DHTML etc.) together and therefore it is left to the developers to make them fit together. Web development is also complicated by the fact that it often has to target multiple browsers on multiple platforms of varying capabilities and syntactic implementations in the support for HTML, CSS, Javascript etc. Finally it is difficult to enforce strong object oriented principles throughout the application, as object-oriented frameworks are usually programmed in a single programming language [14] and basic support for OO-programming do not really exist on the client side. 2.5 Separation of concerns Good application development practices such as separation of concerns are harder to enforce in web applications, especially on the client, side. Code, data and presentation are often intermingled, as this may form (syntactically) perfectly valid documents. Although the web server itself is an example of an implementation of the Model-View-Controller (MVC) pattern [12], which does enforce the separation of the model (business logic, application server, db-server), the view (graphical user interface, the browser) and the controller (event handling, i.e. request dispatching by the web server), the separation is not necessarily enforced through all the application layers. This is especially a problem on the client side, when the amount of client side application logic increases resulting in an increase in Javascript code and DOM manipulation. 2.6 Lack of rich user interface controls Desktop applications that have a rich and responsive user interface are often built using sophisticated controls, which encapsulate complex presentation and event logic. Page 9 / 51 April 2006
  • 10. ITU Project: AJAX – Enhancing interactive web-based applications Numerous such controls exist, some built into the various development tools and many more are available from third party vendors. The user interface controls defined by HTML are pretty basic: text input fields, drop- down lists and radio-buttons and check-boxes. More sophisticated controls can of course be built by aggregating these basic controls into more advanced controls to create e.g. a data-grid using text input fields in a table structure. These aggregated controls, however, will not be as responsive as their desktop control counterparts without the use of client side scripting and a background communication to do silent and incremental updates to the interface. 2.7 Challenges summarized Undoubtedly more issues could be stated as challenges to web application and RIA development, but the ones mentioned above should cover the most important aspects, they are: 1. The browser as an application host 2. The statelessness of web-applications 3. The HTTP request/response model 4. Developer tools and skills 5. Separation of concerns 6. Lack of rich user interface controls These are the aspects we choose to examine in the implementation of our prototypes. Page 10 / 51 April 2006
  • 11. ITU Project: AJAX – Enhancing interactive web-based applications 3 The AJAX concept In order to identify exactly which concepts we are evaluating, an introduction to AJAX as a concept seems to be necessary. In this chapter we will determine exactly what AJAX is and what the scope of AJAX is. We will also provide a technical overview and example of its use. 3.1 The term “AJAX” The term “AJAX” was coined in the article “AJAX: A new approach to Web Applications” [webref3] by Jesse James Garrett in February 2005. According to Mr. Garrett AJAX describes an emerging trend in the way certain technologies are used together. The technologies he refers to are (X)HTML, CSS, DOM, XML, XSLT, XMLHTTPRequest and JavaScript. He defines the concept of AJAX like this: “Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways.” (Garrett [webref3]) However in other literature (especially online articles) there seems to be some uncertainty as to what AJAX really is. AJAX is often described as one specific technology, a framework, a design pattern or “a web development technique” [webref2]. We have chosen to regard AJAX as a general architecture that can be used with interactive web applications. 3.2 What is AJAX all about? Just as there seem to be several opinions on exactly how to describe the concept that the term “AJAX” covers, there are also diverging opinions on the scope of AJAX. However, most sources agree that the core of AJAX is to make asynchronous calls from the browser to the server, thus eliminating the need for a full page refresh at every server communication. This enables a much smoother user experience, which can approach the user experience of a typical windows application. A key element in AJAX to achieve this is the XMLHTTPRequest, which is an object that is accessible from JavaScript that can silently perform background communication based on XML with the server. In fact, even before the term “AJAX” was coined the cornerstones of the AJAX architecture already existed and was referred to as “XMLHTTPRequest”. AJAX is often used in complex web applications with advanced user interfaces. Online examples of AJAX such as Google Maps [webref12], [webref10] and Windows Live Search [webref14] all use extensive graphical user interfaces, which are far beyond what web users typically see in their web browser. This is probably why AJAX is often connected [webref5] with graphical interaction and similar elements created with DHTML and JavaScript. In our understanding AJAX is an architecture that uses asynchronous background communication between the browser and the web server, Page 11 / 51 April 2006
  • 12. ITU Project: AJAX – Enhancing interactive web-based applications nothing more and nothing less. We recognize that it is often used along with advanced DHTML based graphical user interfaces but not always, much like the rich user interface controls in DHTML not necessarily uses AJAX to communicate with the server. In fact most of the rich user interface controls could use JavaScript and full-scale regular post- backs to the server to achieve similar functionality, the only difference being performance and synchronicity (and thus the perceived level of responsiveness). 3.3 AJAX vs. classic web applications After examining the scope of AJAX it is time that we have a look at the structure of an AJAX application as opposed to web applications that does not use AJAX. Most web applications are somewhat dependent on server-side communication. If we look at two popular web-applications, Google Maps [webref12] and Yahoo Maps [webref13] we see a typical example of the difference between a standard server-side internet application and an AJAX based internet application. In Yahoo Maps navigation on the map requires a click the edge of the map, loading a new page with a new map of the requested area. With Google Maps the functionality resembles that of a standard windows map application. Here you can zoom the map and pan it by dragging the map around with the mouse without reloading the page – new map data is retrieved from the server in the background without you noticing it. This is done using an AJAX-like architecture. If we compare the model of a traditional web application to that of an AJAX web application we can see that where the classic model consist of direct interaction between the browser and the web server, the AJAX model uses an AJAX engine (written in JavaScript) to perform XML based communication with the Web Server, and by doing so it can communicate with the server without reloading the entire page. The AJAX Engine usually consists of a JavaScript library Figure 1 Overview of communication in classic and AJAX web that is part of one of the available application models [webref3] AJAX frameworks. However, as a later code example will demonstrate it is also possible, although often not feasible, to write custom made AJAX engine for the individual problem you are solving. Page 12 / 51 April 2006
  • 13. ITU Project: AJAX – Enhancing interactive web-based applications If we analyze what is actually happening in a classic web application and an AJAX web application, we can outline the differences in their architecture. The flow of a typical web application is something like this: 1) The browser sends a request to the server requesting a specific URL. 2) The server handles the request, often by executing server-side code that generates the page. A response is generated and sent back to the client as HTML. 3) The browser loads and displays the entire page returned by the server. 4) User interaction (like a click on a link or a submit button) in the browser sends off new request to the server either using GET or POST methodology. 5) Go to 2. In an AJAX web application the flow would be: 1) The browser sends a request to the server requesting a specific URL. 2) The server handles the request and sends back a generated HTML + JavaScript response, containing among other things a client-side AJAX engine. 3) The browser loads and displays the entire page returned by the server 4) A user interaction that is captured with JavaScript event handling (like a click, a mouse move, a scroll, a keyboard-event, etc.) uses the AJAX engine to send a background request to the server. This step can happen again through out steps 5 and 6. 5) The server handles the background request and returns data as XML. 6) The AJAX engine receives the Figure 2 Here you can see how a typical flow would be XML and can use it to update parts in a classic web application as opposed to an AJAX web of the page without reloading the application [webref3] entire page. Page 13 / 51 April 2006
  • 14. ITU Project: AJAX – Enhancing interactive web-based applications 3.4 Typical Uses of AJAX The qualities that AJAX possesses makes it suited for several typical tasks in web applications. After examining a number of websites using AJAX we have identified 4 typical uses: • Auto completion of Forms In many newer web forms you see AJAX as an assistant that helps visitors fill out forms. This can be in the form of populating a drop-down list with options based on the choices made in other interface elements or it could be a regular auto complete feature that suggests words as you type in a textbox. • Pagination & pre-caching As you move around a set of data AJAX can be the architecture that assist you in silently retrieving the data you are about to navigate to. Examples of this are the results scroll box in our prototype (Chapter 4) and the pan function in Google Maps. • State reporting Often you will see AJAX keeping you updated about the current progress of a server-side process. In our prototype you can notice how the Search button is grayed out while a search is waiting for a response from the server. • Updating server data A lot of AJAX enabled web applications will update data on the server through the use of AJAX calls. A classical example of this is a web content management system in which editors use a browser to edit the web pages and then click a “Save” button to update the page on the server. Naturally AJAX is used for a variety of other tasks as well, but the four mentioned here seems to be very widespread amongst AJAX enabled web applications. In the following code example we will see an example of the AJAX Auto completion of forms. 3.5 Basic Example In order to demonstrate the basic concepts of AJAX we have made a miniature example in ASP.NET with a manually written client-side Javascript AJAX engine. The example demonstrates a simple input form where the user can input personal details. He can enter his name and zip-code. The moment focus leaves the zip- code field, AJAX will connect to a server-side method that looks up the zip-code and returns the appropriate city. If we examine the client-side HTML page, we will find the AJAX engine stored within it. In this case it is a very simple AJAX engine that is customized to the specific task of the server-side page “Lookup.aspx” and updating the next field with the city information. It doesn’t handle errors very well – and it assumes that it receives a valid response from the server. Page 14 / 51 April 2006
  • 15. ITU Project: AJAX – Enhancing interactive web-based applications . . . <script language="javascript" type="text/javascript"> Get the function CheckPostalCode(code){ XMLHttpRequest if(code.length==5){ object in one of two A var http_request; ways due to browser J if (window.XMLHttpRequest) { http_request = new XMLHttpRequest(); compatibility issues. A } else if (window.ActiveXObject) { X http_request = new ActiveXObject("Microsoft.XMLHTTP"); } Make an event http_request.onreadystatechange = function(){ handler for when the if (http_request.readyState == 4) { request is E if (http_request.status == 200) { completed. N document.getElementById('TextBox3').value=http_request.responseText; } else { G alert('An error occurred'); I } Update the DOM } with the city N }; information from the E'GET', 'Lookup.aspx?zip='+code, true); response of the http_request.send(null); background request } } </script> Send the . . . asynchronous <div> request to the Name:<input name="TextBox1" type="text" id="TextBox1" /><br /> server. Zip: <input name="TextBox2" type="text" id="TextBox2" F onblur="CheckPostalCode(this.value);" /><br /> City: <input name="TextBox3" type="text" id="TextBox3" /><br /> O <input type="submit" name="Button1" value="Submit" id="Button1"/> The JavaScript R </div> event that launches . . . the AJAX call. M Whenever focus leaves the input field “TextBox2” it will call the javascript method “CheckPostalCode”. That method creates the XMLHttpRequest Object and sends out an asyncroneus request to the server-side page called “Lookup.aspx”. When a result is retrieved and it is valid it will be put in the “TextBox3”. On the server-side there is the ASP.NET file Lookup.aspx which contains C# code that uses a web service to retrieve city information from the zip-code provided in the Request. Part of the source code of Lookup.aspx can be seen here: Page 15 / 51 April 2006
  • 16. ITU Project: AJAX – Enhancing interactive web-based applications protected void Page_Load(object sender, EventArgs e) Get the ZIP code { from the Request. //Get requested Zip code string zip = Request["zip"]; if (zip != string.Empty) { //Get WebService uszip.USZip ws = new uszip.USZip(); //Return the CITY from the response Response.Write( Lookup the zipcode ws.GetInfoByZIP(zip).SelectSingleNode("//CITY").InnerText); and output the City } (extracted using the } Xpath query ”//CITY”. As an AJAX example the above is about as simple as it can be. Most use of AJAX is a lot more complex which is why the usual approach to implementing it involves using one or more AJAX Frameworks. 3.6 AJAX Frameworks AJAX can easily get quite complex. Not only that, but in its nature it also requires knowledge from the developer of several platforms and languages. If we consider the overall architecture of AJAX, we will note that we are often dealing with server-side code that generates client-side code, that has to work on a lot of different platforms (browsers) and which in turn needs to be able to communicate back with the server-side. This might be doable for smaller tasks like the one we attempted above. But for more advanced scenarios, like those we will examine in our prototype, it is not so easy. This has caused a number of AJAX libraries/frameworks to emerge over the last couple of years. Both open source as well as proprietary. The available frameworks generally fall into two categories: • Pure Javascript-based libraries that can be included in the client-side code but rely on the server-side code to conform to certain standards in the communication (e.g. SOAP or similar protocols). This is mainly toolkits that leave the structure and type of the server-side code up to the individual developer. • Full featured frameworks specific to server-side languages/frameworks. As an example there are several of these frameworks for Microsoft’s ASP.NET. They consist of both server-side parts as well as client-side parts. Most of the ASP.NET frameworks provide a set of AJAX controls that allow the developer to use AJAX without even paying attention to the fact that AJAX is used, or at least that is the intention. In theory the developer can use the AJAX controls just as he would use regular controls – and then just sit back and enjoy the fact that the communication to the server is AJAX enabled, when he runs the application. Page 16 / 51 April 2006
  • 17. ITU Project: AJAX – Enhancing interactive web-based applications 3.7 Advanced AJAX – Design Patterns While AJAX is too general in its nature to be described as a regular design pattern in itself, there are numerous design patterns based on the AJAX architecture. Being a relatively new group of technologies it has proved difficult to find these patterns described in ordinary literature sources, however the website [webref5] is compiling a list of AJAX patterns to be published in a book at some time. In the prototype we have created we have tried to implement a number of these patterns to show an ideal use of AJAX for our evaluation. Some of the patterns discussed at cover methods often used with AJAX – or as a base of AJAX and some show various ways of using AJAX to your advantage. Page 17 / 51 April 2006
  • 18. ITU Project: AJAX – Enhancing interactive web-based applications 4 CASE: Search & Result page In order to evaluate to what degree AJAX solves the problems in creating interactive web applications, we have chosen to create 2 sample web applications solving the same task. One of them uses AJAX technology, the other does not. In the following chapter we will describe their functionality and the challenges we encountered creating the prototypes. The prototypes can temporarily be seen online at . In this chapter we will go through our prototype in details. First we will motivate our choice of application type, discuss the possible points of interactivity followed by an overview of our implementation and the choices we have made implementing it. Finally we will compare the difference in functionality between the AJAX enabled version and the classic search application. 4.1 Website Search One of the most typical web applications is a search & result page. For quite a few websites this is an essential part of the navigation, which is why providing an easy and intuitive user interface is very important. As soon as the information on a website grows beyond a certain number of pages it gets increasingly difficult to make it easily accessible by normal browsing and often the visitors are left with search as the most important navigational facility. As a web application, search functionality requires a certain minimum of user interaction. Traditionally search has been seen as a purely server-side functionality, which has limited the possibility of making interactivity in the user interface. This is one of the reasons we have chosen to examine what AJAX can do for a search web application. Another reason is, that we both have worked intensively with website search in our professional jobs through several years, one of us as a developer on an information-heavy web site the other as a developer for a company that specializes in providing software for website search. 4.2 Interactivity in a search & result page After examining a lot of website search applications we have tried to identify the most common points of interactions, so we could replicate those in our prototype. The primary interaction is of course when the user enters search words and subsequently launches a search for those words. It would appear that a lot of website owners have realized this and have stopped offering advanced search pages and instead offer a search box on every page as an easy way to navigate. After a search is launched results are typically displayed sorted after rank. Some websites display the results in categories, but in order to keep the complexity as low as possible for this prototype, we choose to have uncategorized results. Page 18 / 51 April 2006
  • 19. ITU Project: AJAX – Enhancing interactive web-based applications The next level of interaction happens, when the results are displayed. Sometimes the user will have found too many results and the need arises to narrow the search by filtering out some results. Some of the most typical filters people choose to apply when narrowing a search are the languages and the file types of the results, but the document date is also a popular filter. We have chosen to implement the filters as checkboxes where the selection has an effect on the results returned. Once a result set is displayed pagination is important. Of course the most optimal search engine should return all the relevant results in the first view – but sometimes the user wants to browse through several pages of results to get an idea of what is available – or to find the specific result he is looking for. This is where pagination is needed. It is necessary to provide means to go to the next page of results and back again.. The final interaction that is required in a search web application is the ability to click on a result link and be sent to the correct document. Some would choose to go to a modified version of the document where the search word is highlighted. However for simplicity reasons we have chosen not to implement that feature here. 4.3 Our Implementation When developing a web application the first important choice you have to make is which server-side platform to base it on. We choose to focus on ASP.NET 2.0 because this framework is widely used, several good AJAX toolkits exist for it and it goes a long way in its attempt to provide an object-oriented approach to web application development. Making a full-featured website search engine is not a simple task, so we have decided to use a commercially available search engine to provide the technological foundation for our search and result pages. The search engine is located on a remote server and is available to us through a SOAP Web Service. This has allowed us to focus on the actual implementation of the search and result web application and not so much on the internal workings of a search engine. Since our goal was to design two similar web applications with AJAX being the only difference between them, we began by focusing on reusable parts that we could use for both. One such part was the business logic that could perform the searches and return results. We implemented this in a class that could be utilized by both search applications, called “SearchEngine”. This class exposes the functionality that is needed and it holds a most of the logic needed for working with the Search Web Service. We used the search engine to index a test site. For this purpose we chose and indexed around 5000 pages in 3 different languages and a variety of file formats. The Search Web Service we access programmatically requires a string query (in a proprietary query language) called MQL and it returns a .NET DataSet (a simple in-memory data structure) with the results. The Query string should contain the search query, any filters that need to be applied to the search, the offset of the results and the number of results to return. Page 19 / 51 April 2006
  • 20. ITU Project: AJAX – Enhancing interactive web-based applications The SearchEngine class works in such a way, that in order to make a change to a search performed (e.g. navigation, narrowing of search, etc.) it is necessary to maintain state information containing the last MQL performed so it can be extended with the changes. This also means that it is necessary to persist the state of the model somehow. On both applications we achieved this by storing the SearchEngine as a session parameter. Objects stored in the session storage are automatically persisted by the ASP.NET framework. After isolating the business logic in a shared class we could then focus the code for each application on controller and view logic. Typically in ASP.NET applications the views of the data are defined in an “aspx” file along with ordinary formatting, HTML and CSS. A C# file provides the class definition of the web form class, where the form that makes out the basic container of the web application is defined. Within that, the controller handles input events and data is databound to the view before the page is rendered and the HTTP Response generated. 4.4 Choosing an AJAX Framework Based on our research and the experience we had making the basic example of AJAX functionality in chapter 3, we decided that an AJAX framework was required. We investigated several AJAX frameworks and libraries [webref4, webref6, webref7, webref9] – both standalone and frameworks aimed specifically at .NET and we ended up choosing a framework called “Anthem” [webref6]. This was mainly due to the stability and advanced stage of development we found in this framework. However this field is in a constant state of change because updated versions and new frameworks appear all the time. Anthem basically consists of the following: • A collection of AJAX enabled .NET UI controls, such as textboxes, checkboxes, panels, buttons, etc. These controls will call server-side event handlers through AJAX when a user interacts with them. They can also be updated with new contents when an AJAX response is received. • A .NET attribute that you can attach to server-side methods to make them callable from client side JavaScript code. • A client side JavaScript library that enables the above functionality. It also allows for execution of custom JavaScript code generated by the server side code and sent through AJAX. The general concept in Anthem is that when a button is pressed, or any other kind of AJAX callback to the server is initiated, it will perform a silent post of all the data on the page to the server. Later, when the asynchronous response is received from the server, it will extract only the parts of the response that is marked for updating and use those parts to update the elements on the page that needs updating. The benefit of this is that it requires little change to the server side code, since it appears to the server as if it is a regular post back. The downside is the performance overhead in transmitting all data for the entire page back and forth. Page 20 / 51 April 2006
  • 21. ITU Project: AJAX – Enhancing interactive web-based applications 4.5 Architecture overview The structure of our prototype is pretty simple. As previously mentioned it relies on communication with a remote Web Service. This communication is handled in an automatically generated Web Service Wrapper, which in turn is used in a shared class, SearchEngine, that encapsulates most of the business logic. The classic search application in the class NoAjaxSearch has ordinary browser communication, where as the AjaxSearch class initially dispatches the entire search and result page to the browser, but afterwards maintains background communication using AJAX. Remote Web Service Server Automatically generated Web Service Wrapper SearchEngine NonAjaxSearch AjaxSearch Anthem controls Anthem AJAX engine + custom Javascript Client Browser Client Browser Figure 3. Simplified overview of our prototype architecture Page 21 / 51 April 2006
  • 22. ITU Project: AJAX – Enhancing interactive web-based applications 4.6 Classic Search Web Application On the search & result page that does not use AJAX there are 3 controls that can launch a post back and thereby a search. It’s the search button, and the two pagination buttons. When any of them are clicked the full HTTP post back is performed, and the server-side code performs a new search with the specified parameters. When the Search button is clicked the browser will make a post back to the server where a Button Click event will fire. The method handling the event will gather information from the state of the checkbox controls on the page and then it will perform a new search with the specified search query and the specified language and document type filters. By default it will return the first 10 results found for the first result page. The results are then data bound to a data grid control and later rendered to HTML which is sent to the browser. When either the “Previous Results” link button or the “Next Results” link button is clicked it will fire off a server-side event handler that, based on the original search (stored in the session), will perform a new search but this time it will append to the query that only pages from a certain offset should be returned. For instance this could be results from 20 to 30. It’s possible to narrow the search by un-checking some of the checkboxes and then click the search button again. Figure 4. Classic Search & Result Page 4.7 AJAX Search Web Application Naturally there are a lot of ways to implement AJAX. With the AJAX Search & Result Page we have attempted to implement some of the typical AJAX design patterns that we Page 22 / 51 April 2006
  • 23. ITU Project: AJAX – Enhancing interactive web-based applications have noticed being used at several AJAX based web sites and which is described at the web site “” [webref5]. Some of the design patterns we have been inspired by are: • • • • • Our primary goal was to make all the input controls on the page server-side interactive using AJAX. Secondary goal was to experiment with more flashy AJAX-based functionality that could enhance the overall user experience of the search. Figure 5. AJAX enabled Search & Result Page The Search Button was an easy place to start. We changed the ASP.NET button control with the corresponding Anthem control, and then we set a number of AJAX related properties on it, instructing the Button to be disabled when an AJAX call back to the server was in progress, etc. It was also fairly simple to exchange the checkboxes with Anthem checkboxes and put the results in an Anthem Panel to allow it being updated after an AJAX Response. The main challenges we encountered occurred the moment we wanted to expand on the AJAX functionality beyond what was built-in in the chosen AJAX framework, Anthem. The expanded functionality we attempted to implement was stuff like pagination through a scrollbar and auto completion of the search queries. In the following we will explore the individual interactive items in more details. 4.7.1 Search Box The first point of entry for any user is the text box where the search query is entered. There is little difference between the search box in the AJAX and the classic search application; however we made several attempts of AJAX enabling it. Page 23 / 51 April 2006
  • 24. ITU Project: AJAX – Enhancing interactive web-based applications The first idea we had was to implement an auto complete feature in the textbox, which, as the user would type, would make a drop down suggesting words that was likely to be typed – very much like Google Suggest [ref]. It was supposed to lookup these words from a server-side method, that would either use a list of common search words or a word list extracted from the search database as a basis. However, it turned out that this was beyond the scope of our chosen framework. There are other AJAX frameworks for .NET with that functionality, but we were not sure if they would co-exist with Anthem. We began exploring our options for extending our implementation with this functionality built on top of Anthem. After several attempts we ended up with a lot of complex JavaScript, browser compatibility errors, etc. We also explored JavaScript libraries that claimed to do the trick, but it proved difficult to get them to work with server-side methods as a data source. In the end we concluded, that although it was definitely possible to implement such a control, time would not permit us to do so. The second idea was to implement a Live Search, where a new search would be fired every time a key was pressed in the textbox. Although we again had to extend Anthem to accomplish this we succeeded – but we ended up removing the feature again because we felt it actually decreased the usability of the search application, making it slow and unintuitive. 4.7.2 Search Button In the classic Search application the Search Button is basically a classic submit button. It sends a post back to the server with all the selections made on the form. As mentioned before we naturally started out making this an Anthem control on the AJAX page. But on top of that we also found an opportunity to implement a simple form of state-reporting in it – a common use of AJAX. When it is clicked and a search is launched the text on the Figure 6. The Search button button will change from “Search” to “Searching” and it when an AJAX search is will be disabled to avoid two simultaneous searches being performed launched at once. This was a built-in part of the Anthem button control. 4.7.3 Narrow search functionality When a checkbox is unchecked in the classic search page to narrow the results by either language of file type, nothing will happen until a new search is performed by a click on the search button. The typical checkbox does not post and refresh the entire page when its checked state changes. It is possible with ASP.NET 2.0 checkboxes to make then perform a full post back, but since this is not typical functionality we chose not to. On the AJAX page however it seems logical to fire an asynchronous call back to the server whenever a checkbox state changes. For the user this means that he will save a click every time the need arises to narrow the search. From a development Page 24 / 51 April 2006 Figure 7. The checkboxes that lets the user narrow the search.
  • 25. ITU Project: AJAX – Enhancing interactive web-based applications standpoint it now makes the checkboxes an interactive part of the UI on the same level as a button. They can now fire off events independently of other controls that can modify the model and views. 4.7.4 Results listing and pagination For both applications the results are data bound to an ASP.NET GridView control. It iterates through the table of results in the DataSet and outputs a number of defined fields in a certain layout. A specified number of results are received from the search engine and they are all displayed after the data binding process. On top of the result list a short summary indicates how many results were found out of the total number of pages indexed. This is achieved by data binding to summary information available through the SearchEngine object. But that is where the similarity ends. The classic search page uses two link buttons to control the navigation. Their enabled state is data bound to a property on the SearchEngine object indicating if there are results before/after the currently displayed set. When one of them is clicked it will perform a full page post back to the server where the SearchEngine will be asked to perform the same search as last time, but with another offset on the results returned. In the AJAX application we decided to implement pagination in the form of a scrollbar connected to the server with AJAX, because scrolling seems as an intuitive choice for navigating within a result list. We implemented a server-side method called “MoreResults()” that would retrieve the batch of results and we used the Anthem .NET attribute to make the method available through AJAX in client side JavaScript. Then we used CSS to make a scrollbar on the panel holding the results and followed up by connecting the JavaScript event “OnScroll” to a custom client side method. We realized that we would need global client side variables to keep track of whether another “GetMore” result fetching was in progress and if there even were more results to request at all. We also put a text field below the result list to inform the user that more results was being fetched. 4.8 Summary We have now successfully implemented two search & result applications that are somewhat similar in appearance. One of them is a classic pure server-side implementation with the basic behavior expected of a search & result page, the other has been AJAXified using a widely used AJAX framework plus some amount of custom client-side coding. Parts of the AJAX implementation turned out to be surprisingly simple and easy, such as the introduction of AJAX enabled buttons and checkboxes, while other parts prooved so challenging that we decided against implementing them in the limited time frame we have had available. In the next chapter we will consider how AJAX influences the problems we have identified in making RIAs. Page 25 / 51 April 2006
  • 26. ITU Project: AJAX – Enhancing interactive web-based applications 5. AJAX, the good, the bad and the ugly In this chapter we will revisit the challenges of developing web applications and in particular RIAs outlined in chapter 2. We will reflect upon how the usage of AJAX influences these issues based upon observations and comparisons of our non-Ajax and Ajax-aware prototypes. Each of the issues will be evaluated using the following terms: • Good: Describes aspects that make AJAX a better approach for web application development regarding user experience and/or ease of development. • Bad: Describes aspects of AJAX that are problematic in relation to AJAX web application development and user experience and should be taken into consideration, when choosing whether or not to implement a task using AJAX or not. • Ugly: Describes negative qualities of AJAX that speak unequivalently against the use of AJAX. Of course an aspect of AJAX is not necessarily just good, bad or ugly; depending on the view (usability, ease of development etc.) the same aspect can have both positive and negative traits. We will just attempt to list the different qualities of AJAX, which we have discovered from our prototype development and apply the above terms where applicable. 5.1 The browser as an application host A major problem using the browser as an application host, is the browser navigational/transactional commands (forward/back/refresh/stop) over which the application developer has no control. Ideally the developer would like to have as much control in web applications over available commands as he has in traditional desktop programming, but of course the downside of such control would be that it would leave the user vulnerable to malicious code attacks. In a way AJAX can actually be regarded as an improvement in regard to request retransmission or abortion, in that it gives the developer some control over which requests or application steps shall be recorded in the browser history. Defining some events as AJAX events, which happen silently as background communication, enables that these events will not be repeated by revisiting pages in the browser history. In this way retransmission of critical events could automatically be avoided, however choosing how to handle the possible retransmission of requests in the browser history will still be complicated, since a number of “silent” events will either have to be discarded or reinstated in the user interface from evaluation of possible session state data. The good On the user interface side AJAX will certainly enable a richer and more responsive interface than is possible with a traditional form/hyperlink based HTML approach [11]. In our prototypes this can be seen in the AJAX version where a silent event is fired to the server once the users scrolls the results list past a certain point requesting more results. The results are posted back to the AJAX engine that silently updates the results list to be extended with more results. In this way the browsers normal request/response sequence is Page 26 / 51 April 2006
  • 27. ITU Project: AJAX – Enhancing interactive web-based applications bypassed, which gives the user a more responsive interface, since the page is not locked down (which would normally be the case when waiting for a response). The ability of AJAX to mimic desktop applications will enable applications that feel more natural and familiar for the average user and thereby broaden the user base and hopefully reduce errors. The bad AJAX enables that the developer decides which events of a web application will be part of the browser history; by choosing to implement an event as an AJAX event i.e. doing a silent background communication to update the page, this event is not part of the browser history. This can be an advantage in applications where certain events should not be re- transmitted (e.g. the processing of an order in a web-store), but in other instances it can be confusing to the user who expects normal browser behavior, when using the back/forward buttons to revisit pages. In our prototype all search actions are performed by the AJAX framework and thus none of them are recorded in the browser history and therefore cannot be revisited by using the back/forward buttons. A further negative side effect of this is that a search result can not be recorded as a bookmark Another negative side effect of using Ajax’s silent background communication to update the page is that it may prevent search engines from indexing the information, which is updated dynamically and therefore may become hidden to them, since it is not directly visible in the page source. The ugly Changing the expected behavior of the web browser is by some usability experts such as Jakob Nielsen [webref8] regarded as bad interface practice. It is possible to manually record pages in the browser history by using the fragment identifier part of the URL (that is the part succeeding a hash-sign (#)) and to re-instate this state by manually dealing the fragment identifier changes invoked by navigating through browser history, but it is yet another layer of complexity to deal with for the developer and should ideally be handled by an AJAX framework. 5.2 The statelessness of web applications It can be a challenge to persist the state of objects in a disconnected environment such as the web. Often it will be necessary to serialize the objects that need persistence to a data storage, so they can be recreated at the next request. It’s common for the server-side platforms to provide some means of storing objects in an easy way – either as hidden fields in the requests/response or stored in session based data storage. The good It is possible to create an AJAX application is that it doesn’t require state to be persisted on the server at all! If the interface is not recreated due to a server response, no state is Page 27 / 51 April 2006
  • 28. ITU Project: AJAX – Enhancing interactive web-based applications lost and in that respect the application can behave like a desktop application. Consider our zip-code example (3.5) where is no need for the server to persist statefull information. The bad Statefull information which is managed client side by an AJAX application is lost if the user chooses to refresh the page or tries to navigate using the back/forward buttons; in essence the application is reset to its initial state. Some statefull information needs to be persisted on the server side for security reasons, e.g. it would be a security breach to store information on user authentication and privileges on the client side. The ugly In some cases AJAX can make state management much more complex to handle. This would happen in situations where AJAX requires a client-side state to be maintained as well as a server-side state. One example of this in our prototype is the scrolling functionality of the result-box where more results are retrieved as the scrollbar moves down. An ideal implementation of this functionality would look something like this: 1. User scrolls to a certain point and a scroll event handler is launched. 2. A call is made through AJAX to a server-side method requesting the next 10 results. 3. The server-side method returns only the next 10 results and the client-side code then appends them to the bottom of the results list. That solution would require that a client-side state was maintained and kept in sync with a server-side state – something that does not seem easily achievable in our chosen AJAX framework. This is why the actually implemented solution is like this: 1. User scrolls to a certain point and a scroll event handler is launched 2. The event handler stores the current position of the scrollbar. 3. A call is made through AJAX to a server-side method requesting results from result 0 to the current number of results +10. 4. The server-side method returns all the results requested results and the entire result list is replaced. 5. The position of the scroll bar is restored. 5.3 The HTTP request/response model The main strength of AJAX is its ability to perform asynchronous background communication between the web browser and the server. This is a tremendous advantage in trying to make RIAs with a responsive interface capable of doing partial updates to the interface. The good Page 28 / 51 April 2006
  • 29. ITU Project: AJAX – Enhancing interactive web-based applications With AJAX there is no longer a need for a complete page posting and redrawing in response to a user interaction. It is now possible to allow client-side events independently of each other to affect the server-side model – and to allow the server-side model to update individual views on the page without having the browser refresh the entire page. A good example of this is the use of checkboxes to narrow the search in our prototype. In the classic search page the user would typically have to click the search button and perform a full server post back to have the results affected by the selection made with regards to languages and file types of the search result. In the AJAX implementation however the search result will update on the fly, when the checkboxes change their checked state. The bad This functionality will in many cases improve the functionality a great bit. However it should be used with care. Although it seems to solve a problem in our prototype it’s easy to imagine several scenarios where it might create a problem: • The user might not expect this behavior and be confused. • The user might launch several asynchronous requests that tries to update the same area of his web application The ugly • Since we are dealing with background communication one must be careful when dealing with error-reporting if the request fails. This could especially be a problem with regards to critical transactions (online payments, etc.) • Because the background communication allows the user to keep working with the web application while the request is in progress the client-side state might have changed when the response arrives. An example of this problem can be seen in the zip code look-up example in chapter 3. Imagine the irritation of the user if he has started to type in the field that’s later updated with city information – and the updated city information is incorrect. 5.4 Developer tools and skills To develop RIAs that approach desktop applications in terms of richness and responsiveness of the user interface a thorough understanding of client side as well as server side technologies is necessary. On the client side this means HTML, DHTML, Javascript and in particular the XMLHTTPRequest object. On the server side it means dealing with the requests made by the XMLHTTPRequest object and creating a suiting response to this. From a developers point of view it is important to distinguish between a totally hand- coded AJAX application and one, as our prototype, that is based on a framework that implements AJAX architecture. The former will easily sacrifice ease of development for a rich user interface, because the developer has to “hand-wire” HTML and Javascript. This is however alleviated by the abstraction level defined by a good AJAX framework. The good Page 29 / 51 April 2006
  • 30. ITU Project: AJAX – Enhancing interactive web-based applications A good AJAX framework can hide much of the complexity of the inner workings of AJAX from the developer. Some frameworks facilitate that a non-AJAX page, or parts of it, is converted to an AJAX page simply by substituting AJAX aware controls for the standard HTML controls, and by annotating methods on the server side to be AJAX aware. Of course this is only possible if the controls to be substituted are defined by AJAX versions in the framework. Currently most basic HTML controls can be used in this way in the frameworks, but the number of controls supported will undoubtedly grow as the frameworks mature and will also include sophisticated controls like panes, datagrids etc. as they are known in desktop applications. The bad An AJAX web application is more difficult to develop, evolve and maintain than one based on standard HTML forms [3]. This is especially true, if the application is developed from scratch without the use of one of the available frameworks, but even if a framework is used, the application will still be more complex and harder to read and understand for anyone who is not familiar with the AJAX architecture and the specific framework. Whenever Javascript and DHTML are involved great care has to be taken to be able to support the various discrepancies between browsers and platforms. AJAX relies heavily on both and therefore it is not a trivial task to make a truly cross-browser and cross- platform AJAX application. As an alternative one can choose to provide a non-AJAX version for specific browsers/platforms (and users who have disabled Javascript support) or as a last resort inform the user that this application is not available to him. None of these options are ideal. The Ugly As mentioned in chapter 4.7.1 a second AJAX prototype that would present a “suggest” functionality. For this we required a rich “auto-complete” control that would consist of a text input field and scrollable text area containing a pre-defined number of results, which would be suggested continuously based on what was typed into the text field. The framework we chose to use, Anthem, does not currently contain a pre-built control that satisfies these demands, so building our prototype would require us to build this control ourselves, by aggregating basic HTML controls such as a text input field element and a text area form element coupled with some rather sophisticated Javascript to enable the dynamic updates and the navigation and selection of results. While this task is certainly doable, we found that within the time frame of our project it was simply not feasible to develop even this seemingly simple control from scratch. This really emphasizes to us the necessity of good framework with support for many pre- built controls and puts the finger on a very important “ugly” aspect of using AJAX: It is a very complex and time consuming process. Page 30 / 51 April 2006
  • 31. ITU Project: AJAX – Enhancing interactive web-based applications 5.5 Separation of concerns On the client side all representation of an interface defined by HTML will mix data and representation to a certain level (mostly defined by the usage of CSS), a true separation is not possible. Separation of concerns on the server side is about separating the controller from the model. A web server will do this by default, since it will only handle the dispatch of incoming requests and leave the model processing to the dispatched entity, but since this entity, the application server, is typically also responsible for assembling an updated view to be sent to the client in the response, separation is also about separating code that retrieves, manipulates and produces data from the code that produces formatting, i.e. the definition of the user interface The good Basically AJAX does nothing to improve the separation of concerns; in fact it worsens the problem. However on could argue that since XML is used to handle the transfer of data in the AJAX framework, a great deal of separation is possible between data and user interface; by careful design of an XML-application and the use of XSLT-processing to render the data to a user interface, a large degree of separation is possible at the specification level, but of course the final browser representation would still contain a mix of HTML, CSS and Javascript. Ajax uses Javascript to manipulate the DHTML to update the content of screen elements under Ajax control; as the functions to handle this data transfer can be placed in a separate document, this functionality will not necessarily impede the separation of data and presentation further than a normal form-based HTML document. The bad The web browser elements that need to receive events must specify Javascript code/function calls to initiate the asynchronous background communication. This means that code will be interspersed with HTML and as such degrade the separation of code and representation. Overall AJAX will complicate the server side processing, especially regarding the filtering of events and the creation of views that contain the necessary embedded Javascript code. However in the framework we have used for our AJAX-prototype, Anthem, much of this complexity is shielded from the developer, who only needs to place certain attributes in front of methods to define them as “AJAX-aware” and then Anthem will handle the mapping of events for these methods. The ugly Overall the architecture is undoubtedly complicated by the extra layers of communication introduced by AJAX and by the mixing of Javascript and HTML. A good framework will by its abstraction shield the developer from having to deal with the intermingled code and presentation, but the code and interfaces produced will still have an “ugly” mix of code and presentation. This further emphasizes the necessity for good frameworks that will shield the developer from much of the tedious work involved in gluing together the various parts of an AJAX Page 31 / 51 April 2006
  • 32. ITU Project: AJAX – Enhancing interactive web-based applications application by abstracting core functionality. Furthermore a well tested and feature rich framework will help to restrict the bug hunting to the developers own code and not the nuts-and-bolts of AJAX. 5.6 Lack of rich user interface controls AJAX as a buzzword has often been connected with a rich UI and graphical interaction [webref5]. This is probably due to the fact that a lot of real world web applications that utilize AJAX also use a lot of DHTML features and have very rich UIs e.g. web applications that utilize drag-and-drop, layered pop-ups, etc. There are numerous examples of the term “AJAX” being used synonymously with DHTML – and might cause some confusion. However in our definition AJAX is the architecture that allows for asynchronous Javascript/server-side communication and if we limit ourselves to perceive it that way, AJAX is only responsible for enhancements to UI controls that enable server-side interaction. An example of this is the result list in our prototype. By using AJAX we have built in pagination in the form of a scrollbar, hence making it a rich UI control. The good The ability to perform asynchronous background communication is at the cornerstone of AJAX and this ability makes it possible to develop very responsive UI controls. The bad and ugly Since AJAX by itself does not introduce any new UI controls it really does nothing to improve in this area. The HTML specification does only support very basic UI controls, so any rich UI controls have to be created by aggregation of these basic controls coupled with clever (and complicated) use of Javascript and DHTML. Page 32 / 51 April 2006
  • 33. ITU Project: AJAX – Enhancing interactive web-based applications 6 Future works and limitations In this paper we have focused on a specific limited implementation of AJAX in an attempt to evaluate, if it can be used to enhance interactive web applications. It could be interesting to conduct further studies into the possible uses of AJAX. The prototype we have constructed shows a fairly basic use of AJAX. If time had permitted it, experiments could have been made with more elaborate interfaces containing more interdependent modular screen elements/parts. It would also have been interesting to investigate the use of AJAX in an application that involves multiple transactions e.g. a web store that processes order information such as product selection, user address information, credit card validation etc. In a traditional web store handling the user checkout process typically involves a number of forms the user has to fill in/accept as separate sequential steps; it would be interesting to attempt to make an AJAX enabled checkout process that conceptually consisted of only one page of interdependent modules each handling the various aspects of the checkout process, where the appearance of each module (screen part) would reflect changes made to other modules. A comparison of the various framework implementations that exist for AJAX should also be considered for a complete evaluation of AJAX. A comparison between browser applications made using AJAX and plug-in based alternatives such as Java applets, Macromedia Flash etc. regarding usability and ease of development and system integration would also be a relevant further study to perform. Finally Extensible Application Markup Language (XAML) that is an emerging specification for specifying rich application interfaces that would also substitute an interesting related study. During the work to produce this report we have realized, that any approach to extend the browser’s basic use as a document reader to be employed as a host for RIAs is a compromise between the achieved level of usability and the ease of development. Therefore an interesting future study could be the specification of a new Internet based application host targeted specifically at hosting interactive applications without the limitations incurred by the current web browser. Such a program would of course present many challenges, not least in the area of security, where it would have to attain a security level at least on par with the current web browser and hopefully even better. A well constructed web application host should have a high level of security, an interface that is easy to understand and navigate and cross platform compatibility based on open specifications paired with a coherent and easily extendable architecture. Such a program is sure to be the next killer Internet application! . Page 33 / 51 April 2006
  • 34. ITU Project: AJAX – Enhancing interactive web-based applications 7 Conclusion Until we have a better application host than the one presented by the current browser, developing web applications is a compromise between the amounts of work one can put in to development and how rich and responsive the user interface is required to be. AJAX is a helpful architecture here and now, but can very complex to implement, especially if it is implemented without the use of a good framework, or if functionality is needed, that is not supported by the chosen framework. In terms of code readability AJAX is not a “pretty” solution. What is needed is a better overall web architecture that is more suited to support web applications. AJAX may not be for everyone; if you are developing a web shop you will want to be able to serve the largest user base and therefore you will not want to exclude possible customers from using your site by requiring certain browsers/versions or features such as Javascript, which may be disabled by the security options chosen by some users [3]. As a result you will either have to abandon the use of AJAX completely, use it only for certain optional features on your site that are not required for core functionality or maintain two versions of your web site, which of course is very expensive and to may also introduce discrepancies between the different versions. Page 34 / 51 April 2006
  • 35. ITU Project: AJAX – Enhancing interactive web-based applications 8 Literature 8.1 Regular Sources [1] CHO, KIM et al. 1997. Object-Oriented Web Application Architectures And Development Strategies. [2] Costagliola, Ferrucci, Francese. 2002. Web Engineering: Models and Methodologies for the Design of Hypermedia Applications. Handbook of Software Engineering & Knowledge Engineering, University of Pittsburgh. [3] DREYFUS, P. 1998. Industry report: THE SECOND WAVE Netscape on Usability in the Services-Based Internet. IEEE INTERNET COMPUTING Vol. 2, No. 2, March/April 1998. [4] Fuchs, Matthew. 1998. Building an Information System from the Web. IEEE. [5] Fuchs, Matthew. 1996. Let's talk: Extending the Web to Support Collaboration. IEEE. [6] Fielding, Taylor. 2000. Principled Design of the Modern Web Architecture. ACM. [7] Furht, Phoenix, Yin et al. 2000. An Innovative Internet Architecture for Application Service Providers. IEEE: Proceedings of the 33rd Hawaii International Conference on System Sciences. [8] Krikelis, Argy. 1998. High-performance multimedia applications and the Internet. IEEE. [9] Murugesan, Deshpande, Hansen and Ginige. 2001. Web Engineering: A New Discipline for Development of Web-based Systems. Lecture Notes in Computer Science, Springer Berlin / Heidelberg. [10] Ollmann, Gunter. 2003. Best Practice in Managing HTTP-Based Client Sessions. Elsevier Science, Network Security, Volume 2003, Number 6, June 2003, pp. 13-17(5). [11] Paulson, Linda Dailey. 2005. Building Rich Web Applications with Ajax. IEEE Computer Society. [12] Phatak, Esakki, et al. 2001. Web&: An Architecture for Non-Interactive Web. IEEE. [13] Preciado, Linaje, et al. 2005. Necessity of methodologies to model Rich Internet Applications. IEEE. Proceedings of the 2005 Seventh IEEE International Symposium on Web Site Evolution (WSE’05). [14] Schwabe, Rossi, et al. 2001. Web Design Frameworks: An Approach to Improve Reuse in Web Applications. Lecture Notes in Computer Science, Springer Berlin / Heidelberg. Page 35 / 51 April 2006
  • 36. ITU Project: AJAX – Enhancing interactive web-based applications 8.2 Sources on the Web Due to the fact that we have only been able to find fairly little academic literature on the subject of Rich Internet Applications and AJAX we have had to examine other sources such as blogs, commercial articles and Wikipedia as well. [webref1] Wikipedia: RIA [webref2] Wikipedia: AJAX [webref3] Garrett, J.J. 1998. Ajax: A New Approach to Web Applications. In Adaptive Path website. [webref4] (Microsoft). Atlas Framework. [webref5] (Multiple authors), Mahemoff (Editor): AJAX Patterns Wiki. [webref6] (Multiple authors). Anthem Framework. [webref7] (Multiple authors). Rico Framework. [webref8] Nielsen, J. 2000. Jakob Nielsen's Alertbox, October 29, 2000 [webref9] Zeis, Daniel. 2006. ASP.NET AJAX framework comparison. 8.3 Web Applications As part of our research we have examined several popular web applications – some of them use AJAX, some of them do not. [webref10] An online text editor using AJAX. [webref11] Google Suggest Page 36 / 51 April 2006
  • 37. ITU Project: AJAX – Enhancing interactive web-based applications Global search engine with AJAX based autocomplete. [webref12] Google Maps AJAX based map service. [webref13] Yahoo Maps Classic map service, not using AJAX. [webref14] Windows Live Search Portal and search application using AJAX. [webref15] Pageflakes AJAX based portal [webref16] Orangoo Spell Check AJAX based online spell checker. Page 37 / 51 April 2006
  • 38. ITU Project: AJAX – Enhancing interactive web-based applications 9 Glossary ASP.NET Active Server Pages .Net: A Microsoft’s development platform for web applications loosely based on the original ASP scripting language. ASP.NET is based on Microsoft’s all encompassing .NET development platform. CSS Cascading Style Sheet: A stylesheet language used to describe the presentation of a document written in a markup language. (Wikipedia) DHTML Dynamic Hypertext Markup Language: Manipulation of a HTML page by adding and modifying elements and properties using Javascript and the DOM (see DOM). DOM Document Object Model: A programmatic model that describes a HTML page as a tree structure of objects representing the interface elements. HTML Hyper Text Markup Language: A language for specifying documents that can be interlinked through hyperlinks. HTTP Hyper Text Transfer Protocol: The protocol that is (primarily) used for communication on the World Wide Web. Javascript A scripting language invented by Netscape Communications Corporation. Support for Javascript is built into all modern browsers and is used for client side processing. JSP JavaServer Pages: A Java based language for developing server-side application logic for web applications. Post back The process of transmitting an HTML form to the server. SOAP Simple Object Access Protocol: A protocol for exchanging XML- based messages over a computer network. Has become more or less the de-facto standard for web-services communication. TP monitor Transaction Processing monitor: A program that handles client/server communication and transactions typically in a large scale computer system (mainframes). XHTML Extensible Hyper Text Markup Language: A stricter version of HTML conforming to XML restrictions. XML eXtensible Markup Language: A WC3 recommended standard for creating special purpose markup languages (Wikipedia). XSLT eXtensible Markup Language Transformations: An XML-based language for transforming XML. XMLHTTPRequest An interface for XML based communication over HTTP. Can be used in modern browsers via Javascript. URL Uniform Resource Locator: a string of characters conforming to a standardized format, which refers to a resource on the Internet (Wikipedia). Page 38 / 51 April 2006
  • 39. ITU Project: AJAX – Enhancing interactive web-based applications 10 Appendix: Source code for prototype 10.1 SearchEngine.cs The shared library that uses a web service wrapper to access the search web service. using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; /// <summary> /// The class that provides access to the search engine /// </summary> public class SearchEngine { #region Members private ws.SearchService service; //Automatically generated Web Service Wrapper private DataSet resultSet; //The dataset with the last Search Results private string license; //The license key to the Web Service. private string initMQL; //The initial query sent to the Web Service. private int resultsPerPage; //Default number of Results to display per result page private string lastMQL; //The last query executed. Used when narrowing or navigating a search private bool hasSearched; //Keeps track of if a search has been performed. #endregion #region Properties /// <summary> /// Property accessor to the Search Results. Used in the DataBinding of results. /// </summary> public DataSet ResultSet { get{ return resultSet; } } /// <summary> /// Returns state information. /// </summary> public bool HasSearched { get { return hasSearched; } } /// <summary> /// Used to change the default number of results shown per page /// </summary> public int ResultsPerPage{ get{ return resultsPerPage;} set{ resultsPerPage=value; } } /// <summary> /// Performs a check to see if we have valid results in the result set. /// </summary> public bool HasResults { get { if (resultSet == null) return false; Page 39 / 51 April 2006
  • 40. ITU Project: AJAX – Enhancing interactive web-based applications if (!resultSet.Tables.Contains("Pages")) return false; return true; } } /// <summary> /// Returns true if there are results before the ones being displayed now. /// </summary> public bool CanMovePrevious { get{ return (bool)(FirstPageRequested > 0); } } /// <summary> /// Returns true if there are more results /// </summary> public bool CanMoveNext { get { return (bool)(LastPageRequested < PagesFound); } } /// <summary> /// Retrieves the number of pages found from the Summary table /// </summary> public int PagesFound { get { if (!HasResults) return 0; return (int)resultSet.Tables["Summary"].Rows[0][1]; } } /// <summary> /// Return the number of pages in the database from the Summary table /// </summary> public int PagesInDatabase { get { if (!HasResults) return 0; return (int)resultSet.Tables["Summary"].Rows[1][1]; } } /// <summary> /// Returns the last MQL executed /// </summary> public string MQLExecuted { get { if (!HasResults) return ""; return resultSet.Tables["PerformedSearch"].Rows[0][0].ToString(); } } /// <summary> /// Returns the current offset in the Search results /// </summary> public int FirstPageRequested { get { if (!HasResults) return 0; return int.Parse(resultSet.ExtendedProperties["FirstPage"].ToString()); } } Page 40 / 51 April 2006
  • 41. ITU Project: AJAX – Enhancing interactive web-based applications /// <summary> /// Returns the number of the last result requested /// </summary> public int LastPageRequested { get { if (!HasResults) return 0; return FirstPageRequested+int.Parse(resultSet.ExtendedProperties["MaxPages"].ToString()); } } #endregion /// <summary> /// Generate MQL for Languages /// </summary> /// <param name="Languages">List of Languages</param> /// <returns>A string of MQL</returns> private string GenerateLanguageMQL(List<String> Languages) { string rt = " LANGUAGES CLEAR "; Languages.ForEach(delegate(string s) { rt += "'" + s + "' "; }); return rt; } /// <summary> /// Generate MQL for Filetypes /// </summary> /// <param name="Filetypes">List of Filetypes</param> /// <returns>A string of MQL</returns> private string GenerateFiletypeMQL(List<String> Filetypes) { string rt = " FILTERS CLEAR "; Filetypes.ForEach(delegate(string s) { rt += "@HTTP_MIMETYPE CONTAINS '" + s + "' OR "; }); return rt; } /// <summary> /// Performs a search based on the MQL provided. /// </summary> /// <param name="MQL">The MQL to Search for</param> private void Search(string MQL) { //Call the Web Service Wrapper to perform the search. resultSet=service.Search(license, "", false, "", lastMQL+" LIMITS MaxResults="+resultsPerPage.ToString()+" OPTIONS "+MQL); hasSearched = true; lastMQL = MQLExecuted.Trim()+" "; } /// <summary> /// Narrow the search by apply Language and Filetype filters /// </summary> /// <param name="Languages">Languages to search for</param> /// <param name="Filetypes">Filetypes to search for</param> public void NarrowSearch(List<String> Languages, List<String> Filetypes) { string mql = ""; if (Languages != null) mql += GenerateLanguageMQL(Languages); if (Filetypes != null) mql += GenerateFiletypeMQL(Filetypes); Search(mql); } /// <summary> /// Launch a new search /// </summary> /// <param name="Query">Query to search for</param> /// <param name="Languages">List of languages to search for</param> Page 41 / 51 April 2006
  • 42. ITU Project: AJAX – Enhancing interactive web-based applications /// <param name="Filetypes">List of Filetypes to search for</param> public void NewSearch(string Query, List<String> Languages, List<String> Filetypes) { lastMQL = initMQL; Search(" SearchQuery='" + Query.Replace("'", "") + "' " + this.GenerateLanguageMQL(Languages) + this.GenerateFiletypeMQL(Filetypes)); } #region Navigation /// <summary> /// Performs the last search with a different offset /// </summary> public void MovePrevious() { Search("LIMITS FirstResult="+((int)(FirstPageRequested- resultsPerPage)).ToString()); } /// <summary> /// Fills More data in the Pages Table /// </summary> /// <returns>true if there are more results</returns> public bool GetMoreResults() { if (resultSet == null) return false; if (resultSet.Tables["Pages"].Rows.Count == PagesFound) return false; //Get additional results DataSet ds = service.Search(license, "", false, "", lastMQL + " LIMITS MaxResults=" + resultsPerPage.ToString() + "LIMITS FirstResult=" + resultSet.Tables["Pages"].Rows.Count.ToString()); //Merge new results with old resultSet.Tables["Pages"].Merge(ds.Tables["Pages"], false, MissingSchemaAction.Add); return true; } /// <summary> /// Performs the last search with a different offset /// </summary> public void MoveNext() { Search("LIMITS FirstResult=" + ((int)(LastPageRequested)).ToString()); } #endregion /// <summary> /// Constructor. Initializes member variables, creates Wrapper object to webservice, Loads configuration. /// </summary> public SearchEngine() { //Initialize members service = new ws.SearchService(); license = ConfigurationManager.AppSettings["license"]; initMQL = ConfigurationManager.AppSettings["InitMQL"]; resultsPerPage= int.Parse(ConfigurationManager.AppSettings["ResultsPerPage"]); lastMQL = initMQL; hasSearched = false; } } Page 42 / 51 April 2006
  • 43. ITU Project: AJAX – Enhancing interactive web-based applications 10.2 NoAjaxSearch.aspx The user interface for the classic search page. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NoAjaxSearch.aspx.cs" Inherits="NoAjaxSearch" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" > <head runat="server"> <title>Basic Search & Result Page</title> </head> <body style="font-size: x-small; font-family: Verdana, Arial"> <form id="form1" runat="server"> <div> <table width="100%"> <tr> <td style="width: 120px"> </td> <td style="font-weight: bold; font-size: large; width: 603px; text-align: center"> No AJAX Search &amp; Results page<br /> </td> <td style="width: 120px"> </td> </tr> <tr> <td style="width: 120px"> </td> <td style="border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; width: 603px; border-bottom: black thin solid"> <table width="100%"> <tr> <td style="width: 188px; font-weight: bold; color: white; background-color: #1c5e55;" valign="top"> Enter search query:<br /> <asp:TextBox ID="SearchQueryField" runat="server" BackColor="#E3EAEB" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small" Width="112px"></asp:TextBox> <asp:Button ID="SearchButton" runat="server" OnClick="SearchButton_Click" Text="Search" /><br /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="SearchQueryField" Display="Dynamic" ErrorMessage="Enter one or more search words" Width="184px"></asp:RequiredFieldValidator><br /> <br /> Document Types<br /> <asp:CheckBoxList ID="TypeList" runat="server"> <asp:ListItem Selected="True" Value="application/pdf">Adobe PDF</asp:ListItem> <asp:ListItem Selected="True" Value="msword">Microsoft Word</asp:ListItem> <asp:ListItem Selected="True" Value="msexcel">Microsoft Excel</asp:ListItem> <asp:ListItem Selected="True" Value="mspowerpoint">Microsoft PowerPoint</asp:ListItem> <asp:ListItem Selected="True" Value="text/html">Web Pages</asp:ListItem> </asp:CheckBoxList><br /> Language<br /> <asp:CheckBoxList ID="LanguageList" runat="server" Width="120px"> <asp:ListItem Selected="True" Value="en">English</asp:ListItem> <asp:ListItem Selected="True" Value="da">Danish</asp:ListItem> <asp:ListItem Selected="True" Value="sv">Swedish</asp:ListItem> </asp:CheckBoxList><br /> <br /> <br /> </td> <td valign="top"> Page 43 / 51 April 2006
  • 44. ITU Project: AJAX – Enhancing interactive web-based applications <asp:Panel ID="ResultsPanel" runat="server" Height="100%" Width="100%" Visible='<%#engine.HasResults %>'> <table width="100%"> <tr> <td colspan="3" style="height: 14px"> <asp:Label ID="SummaryLabel" runat="server" Text='<%#String.Format("Found {0} of {1} results", engine.PagesFound, engine.PagesInDatabase) %>' Font- Bold="True"></asp:Label></td> </tr> <tr> <td style="height: 14px; width: 33%;"> <asp:LinkButton ID="PreviousBtn" runat="server" Font-Bold="True" Enabled='<%# engine.CanMovePrevious %>' OnClick="PreviousBtn_Click">[Previous]</asp:LinkButton></td> <td align="center" style="height: 14px">Results <%#(int)(engine.FirstPageRequested+1) %> to <%#(engine.LastPageRequested>engine.PagesFound)?engine.PagesFound:engine.LastPageRequeste d %> </td> <td align="right" style="height: 14px; width: 33%;"> <asp:LinkButton ID="NextBtn" runat="server" Font-Bold="True" Enabled='<%# engine.CanMoveNext %>' OnClick="NextBtn_Click">[Next]</asp:LinkButton></td> </tr> <tr> <td colspan="3" style="height: 154px" valign="top"> <asp:GridView ID="ResultsGrid" runat="server" Width="100%" AutoGenerateColumns="False" DataMember="Pages" DataSource='<%# (engine.HasResults)?engine.ResultSet:null %>' CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5"> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <Columns> <asp:TemplateField> <ItemStyle Width="15px" /> <ItemTemplate> <%# (((int)Eval("PageNo"))+1) %> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="CultureName"> <ItemStyle Width="15px" /> </asp:BoundField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("LinkDisplay") %>' Text='<%# Eval("Title") %>'></asp:HyperLink><br /> <%# Eval("Description") %><br /> <em><%# Eval("@HTTP_MIMETYPE") %></em> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:BoundField DataField="SizeAsString" HeaderText="Size"> <ItemStyle Width="40px" /> </asp:BoundField> </Columns> <RowStyle BackColor="#E3EAEB" /> <EditRowStyle BackColor="#7C6F57" /> <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> </td> </tr> <tr> <td style="height: 21px"> </td> <td style="height: 21px"> </td> <td style="height: 21px"> </td> </tr> </table> </asp:Panel> Page 44 / 51 April 2006
  • 45. ITU Project: AJAX – Enhancing interactive web-based applications <br /> </td> </tr> </table> </td> <td style="width: 120px"> </td> </tr> </table> </div> </form> </body> </html> 10.3 NoAjaxSearch.cs The code-behind for the classic search page. using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; public partial class NoAjaxSearch : System.Web.UI.Page { /// <summary> /// Create, store and access the SearchEngine object in the Session State /// </summary> protected SearchEngine engine { get { if (Session["engine"] == null) Session["engine"] = new SearchEngine(); return (SearchEngine)Session["engine"]; } } protected void Page_Load(object sender, EventArgs e) { //Assign event handler this.PreRender += new EventHandler(_Default_PreRender); //Reset session if called again if (!this.IsPostBack) Session.Clear(); } void _Default_PreRender(object sender, EventArgs e) { //Do the databinding ResultsPanel.DataBind(); } protected void SearchButton_Click(object sender, EventArgs e) { //Launch an initial search engine.NewSearch(SearchQueryField.Text, GetLanguages(), GetFileTypes()); Page 45 / 51 April 2006
  • 46. ITU Project: AJAX – Enhancing interactive web-based applications } protected void PreviousBtn_Click(object sender, EventArgs e) { //Handle Pagination engine.MovePrevious(); } protected void NextBtn_Click(object sender, EventArgs e) { //Handle Pagination engine.MoveNext(); } /// <summary> /// Make a list of languages checked /// </summary> /// <returns>List of language names</returns> private List<String> GetLanguages() { List<String> Lang = new List<string>(); foreach (ListItem li in LanguageList.Items) { if (li.Selected) { Lang.Add(li.Value); } } return Lang; } /// <summary> /// Make a list of filetypes checked /// </summary> /// <returns>List of filetypes</returns> private List<String> GetFileTypes() { List<String> Types = new List<string>(); foreach (ListItem li in TypeList.Items) { if (li.Selected) { Types.Add(li.Value); } } return Types; } } 10.4 AjaxSearch.aspx The user interface for the AJAX search page. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxSearch.aspx.cs" Inherits="AjaxSearch" %> <%@ Register Assembly="Anthem" Namespace="Anthem" TagPrefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" > <head runat="server"> <title>AJAX Search & Result Page</title> <script type="text/javascript" language="javascript"> var Fetching=false; var MoreResults=true; function GetMore(panel) { if(!Fetching){ if(MoreResults){ if((panel.scrollTop+panel.offsetHeight)>(panel.scrollHeight-300)){ Page 46 / 51 April 2006
  • 47. ITU Project: AJAX – Enhancing interactive web-based applications //Set Fetching to make sure we don't try this twice at the same time Fetching=true; var; //Remember scroll position var Origscroll=panel.scrollTop; //Update status document.getElementById('statusfld').innerHTML='Retrieving more results'; Anthem_InvokePageMethod('GetMoreResults',[], function(result) { //Reset scroll position since the entire panel have been updated document.getElementById(p).scrollTop=Origscroll; MoreResults=result.value; document.getElementById('statusfld').innerHTML='<br/>'; Fetching=false; } ); } } } } </script> </head> <body style="font-size: x-small; font-family: Verdana, Arial"> <form id="form1" runat="server"> <div> <table width="100%"> <tr> <td style="width: 120px"> </td> <td style="font-weight: bold; font-size: large; text-align: center"> AJAX Search &amp; Results page<br /> </td> <td style="width: 120px"> </td> </tr> <tr> <td style="width: 120px"> </td> <td style="border-right: black thin solid; border-top: black thin solid; border-left: black thin solid;border-bottom: black thin solid"> <table width="100%" border="1"> <tr> <td style="width: 200px;height:500px;font-weight: bold; color: white; background-color: #1c5e55;" valign="top"> Enter search query:<br /> <asp:TextBox ID="SearchQueryField" runat="server" BackColor="#E3EAEB" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small" Width="80px"></asp:TextBox> <cc1:Button ID="SearchButton" runat="server" EnabledDuringCallBack="false" TextDuringCallBack="Searching" OnClick="SearchButton_Click" Text="Search" /><br /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="SearchQueryField" Display="Dynamic" ErrorMessage="Enter one or more search words" Width="184px"></asp:RequiredFieldValidator><br /> <br /> Document Types<br /> <cc1:CheckBox ID="pdfChk" runat="server" AutoCallBack="true" Text="Adobe PDF" Checked="true" OnCheckedChanged="TypeList_SelectedIndexChanged" /><br /> <cc1:CheckBox ID="mswordChk" runat="server" AutoCallBack="true" Text="Microsoft Word" Checked="true" OnCheckedChanged="TypeList_SelectedIndexChanged" /><br /> <cc1:CheckBox ID="msexcelChk" runat="server" AutoCallBack="true" Text="Microsoft Excel" Checked="true" OnCheckedChanged="TypeList_SelectedIndexChanged" /><br /> Page 47 / 51 April 2006
  • 48. ITU Project: AJAX – Enhancing interactive web-based applications <cc1:CheckBox ID="mspowerpointChk" runat="server" AutoCallBack="true" Text="Microsoft PowerPoint" Checked="true" OnCheckedChanged="TypeList_SelectedIndexChanged" /><br /> <cc1:CheckBox ID="htmlChk" runat="server" AutoCallBack="true" Text="Web Pages" Checked="true" OnCheckedChanged="TypeList_SelectedIndexChanged" /> <br /> <br /> Language<br /> <cc1:CheckBox ID="enChk" runat="server" AutoCallBack="true" Text="English" Checked="true" OnCheckedChanged="LanguageList_SelectedIndexChanged" /><br /> <cc1:CheckBox ID="daChk" runat="server" AutoCallBack="true" Text="Danish" Checked="true" OnCheckedChanged="LanguageList_SelectedIndexChanged" /><br /> <cc1:CheckBox ID="svChk" runat="server" AutoCallBack="true" Text="Swedish" Checked="true" OnCheckedChanged="LanguageList_SelectedIndexChanged" /><br /> <br /> <br /> </td> <td valign="top"> <asp:Panel ID="ResultsPanel" runat="server" Height="100%" Width="100%" > <table width="100%"> <tr> <td style="height: 14px"> <cc1:Label ID="SummaryLabel" AutoUpdateAfterCallBack="true" runat="server" Visible='<%#engine.HasResults %>' Text='<%#String.Format("Found {0} of {1} results", engine.PagesFound, engine.PagesInDatabase) %>' Font-Bold="True"></cc1:Label></td> </tr> <tr> <td style="height: 154px; width:100%" valign="top"> <cc1:Panel ID="ScrollPanel" runat="server" onscroll="GetMore(this)" Height="450px" Width="100%" ScrollBars="Vertical" Visible='<%#engine.HasResults %>' AutoUpdateAfterCallBack="true"> <asp:GridView ID="ResultsGrid" runat="server" Width="95%" AutoGenerateColumns="False" DataMember="Pages" DataSource='<%# (engine.HasResults)?engine.ResultSet:null %>' CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5" ShowHeader="false"> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <Columns> <asp:TemplateField> <ItemStyle Width="15px" /> <ItemTemplate> <%# (((int)Eval("PageNo"))+1) %> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="CultureName"> <ItemStyle Width="15px" /> </asp:BoundField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("LinkDisplay") %>' Text='<%# Eval("Title") %>'></asp:HyperLink><br /> <%# Eval("Description") %><br /> <em><%# Eval("@HTTP_MIMETYPE") %></em> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:BoundField DataField="SizeAsString" HeaderText="Size"> <ItemStyle Width="40px" /> </asp:BoundField> </Columns> <RowStyle BackColor="#E3EAEB" /> <EditRowStyle BackColor="#7C6F57" /> Page 48 / 51 April 2006
  • 49. ITU Project: AJAX – Enhancing interactive web-based applications <SelectedRowStyle BackColor="#C5BBAF" Font- Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> </cc1:Panel> <div id="statusfld"><br /></div> </td> </tr> </table> </asp:Panel> </td> </tr> </table> </td> <td></td> </tr> </table> </div> </form> </body> </html> 10.5 AjaxSearch.cs The code-behind for the AJAX search page. using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; public partial class AjaxSearch : System.Web.UI.Page { /// <summary> /// Create, store and access the SearchEngine object in the Session State /// </summary> protected SearchEngine engine { get { if (Session["engine"] == null) { SearchEngine se = new SearchEngine(); se.ResultsPerPage = 20; Session["engine"] = se; } return (SearchEngine)Session["engine"]; } } protected void Page_Load(object sender, EventArgs e) { //Assign event handler this.PreRender += new EventHandler(_Default_PreRender); //Reset session if called again if (!this.IsPostBack) Session.Clear(); Page 49 / 51 April 2006
  • 50. ITU Project: AJAX – Enhancing interactive web-based applications } void _Default_PreRender(object sender, EventArgs e) { //Do the databinding ResultsPanel.DataBind(); //Set the Anthem ScrollPanel to be updated when the AJAX callback returns. ScrollPanel.UpdateAfterCallBack = true; } protected void SearchButton_Click(object sender, EventArgs e) { //Launch an initial search engine.NewSearch(SearchQueryField.Text, GetLanguages(), GetFileTypes()); //Set JavaScript code to be executed client side. ' //The code updates the global variable MoreResults Anthem.Manager.AddScriptForClientSideEval("MoreResults="+engine.CanMoveNext.ToString().To Lower()+";"); } /// <summary> /// Eventhandler that handles when a filetypes checkbox has been checked or unchecked /// </summary> protected void TypeList_SelectedIndexChanged(object sender, EventArgs e) { if (engine.HasSearched) { engine.NarrowSearch(null,GetFileTypes()); } } /// <summary> /// Make a list of languages checked /// </summary> /// <returns>List of language names</returns> private List<String> GetLanguages() { List<String> Lang = new List<string>(); if (enChk.Checked) Lang.Add("en"); if (daChk.Checked) Lang.Add("da"); if (svChk.Checked) Lang.Add("sv"); return Lang; } /// <summary> /// Make a list of filetypes checked /// </summary> /// <returns>List of filetypes</returns> private List<String> GetFileTypes() { List<String> Types = new List<string>(); if (pdfChk.Checked) Types.Add("pdf"); if (mswordChk.Checked) Types.Add("msword"); if (msexcelChk.Checked) Types.Add("msexcel"); if (mspowerpointChk.Checked) Types.Add("mspowerpoint"); if (htmlChk.Checked) Types.Add("html"); return Types; } /// <summary> /// Eventhandler that handles when a language checkbox has been checked or unchecked /// </summary> protected void LanguageList_SelectedIndexChanged(object sender, EventArgs e) { if (engine.HasSearched) { engine.NarrowSearch(GetLanguages(),null); } Page 50 / 51 April 2006
  • 51. ITU Project: AJAX – Enhancing interactive web-based applications } /// <summary> /// Anthem Method that is callable from client side JavaScript. /// Retrieves more results and updates scrollpanel with more pages. /// </summary> /// <returns>True if there are more results</returns> [Anthem.Method] public bool GetMoreResults() { bool b = engine.GetMoreResults(); return b; } } Page 51 / 51 April 2006