This presentation introduces AJAX (Asynchronous JavaScript and XML) explaining the details of implementation and constraints in design and also present a sample example for coding a simple ajax powered web page.
1. A J A X
Asynchronous Javascript And XML
www.rohitsinha.com
2. WHAT IS AJAX ?
Original Name: XMLHttpRequest
Started up by: Microsoft shipped IE5
Now Almost all browsers supports it
Jesse James Garrett named it AJAX in an essay
(http://www.adaptivepath.com/ideas/essays/archive
s/000385.php)
No reloads required to get/send data to server
You can interact with the website while it
is requesting data from server
4. Still Not Impressed ?
Some More Beauties !!!
1. Backbase’s RSS Reader. Only a demo, so you can’t add your
own feeds.
2. Backpack. To do list organizer and simple project management
application. Includes email and mobile reminders.
3. Writely. Online word processor. Google bought it and now its
Google Docs.
4. Amazon Zuggest. Francis Shanahan’s version of Google
Suggest–but for Amazon.
5. TimeTracker. Personal time management tool.
6. Del.icio.us Director. Rich UI for managing your del.icio.us links.
7. Protopage. Another twist on an information portal.
6. AJAX Approach
Server response back to
browser which is displayed
instantly
Response 1
Request 3
Request 2 Response 2
Request 1
Response 3
User request
something from
server
7. Technologies Behind AJAX
Garrett’s article mentions several technologies that he sees as parts of an Ajax
solution. These are:
:
HTML/XHTML
❑ HTML/XHTML: Primary content representation languages
❑ CSS: Provides stylistic formatting to XHTML
❑ XML: Data exchange format
DOM
❑ XSLT: Transforms XML into XHTML (styled by CSS)
❑ XMLHttp: Primary communication broker
JAVASCRIPT
❑ JavaScript: Scripting language used to program an Ajax engine
The other technologies in the list are helpful in fine-tuning an Ajax
solution, but
they aren’t necessary.
8. AJAX PRINCIPLES
Michael Mahemoff (www.mahemoff.com), a software developer and usability expert,
identified several key principles of good Ajax applications that are worth
repeating:
Minimal Traffic
No Surprises
Established Conventions
No Distraction
Accessibility
Avoid Entire Page Download
User First
9. Why Should I Use Ajax?
Partial Page Updating
Invisible Data Retrieval
Constant Updating
Smooth Interfaces
Simplicity & Rich Functionality
Drag & Drop
15. SUPPORT FOR
XMLHttpRequest OBJECT
check the
create the
create the YES browser NO XMLHttpRequest
XMLHttpRequest ’s
object using native
object using support of
JavaScript object
ActiveX ActiveX
technique
objects
16. CREATING XMLHttpRequest
Object
var xhr = false;
function createXMLHttpRequest()
{
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
17. REQUESTING THE SERVER
If(xhr)
{
xhr.onreadystatechange = showFunction;
xhr.open(“GET”, “filename”, true);
xhr.send(null);
}
else
{
document.getElementById(“AjaxUpdateArea”).innerHTML =
“Sorry unable to create XMLHttpRequest”;
}
}
18. RESPONSE FROM SERVER
function showFunction()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var outMsg = xhr.responseText;
}
else
{
outMsg = “Unable to get response from server”;
}
document.getElementById(“AjaxUpdateArea”).innerHTML =
outMsg;
}
}
20. WHY NOT AJAX ?
• Poor Responsiveness
• Breaks the Back Button on Your Browser
• Breaking Bookmarks and Blocking Search
Engine Indexes
• Strain on the Browser
21. Where To Go From Here
Sites:
• 100 Ajax Tutorials and Resources
• 126 Ajax Tutorials And Resources To Help You Learn
And Use Ajax
• Ajaxian
• YUI Library – Yahoo! User Interface Library
Books:
• Ajax in action
• Ajax Hacks
• Head Rush Ajax
• Foundation Of Ajax
• Apress Beginning AJAX with PHP From Novice to
Professional
22. Thank You
Refrences:
• Beginning Ajax (Programmer to Programmer) •Lynda – Ajax Essential Training
• Wrox Professional Ajax 2nd Ed Videos
• Foundations Of Ajax • Ajax Crash Course By SitePoint
• Head First Ajax • www.ajaxpatterns.org
• Head Rush Ajax • www.ajaxmatters.com
• Apress Beginning AJAX with • www.learn-ajax-tutorial.com
PHP From Novice to Professional • www.ajaxwith.com
• Ajax in Action
Notas do Editor
Web Technologies(07CSC604) Presentation on AJAX Technology. Presented on: 12 April, 2010
What AJAX is? Ajax in its original name is XMLHttpRequest started up when microsoft shipped IE5 it has cool capability where without leaving a webpage it can go talk to a server get some data and come back without reloading entire page. Over the years other browser developers found this concept very useful and they also implemented it and now almost every browser supports it. A guy named Jesse James Garrett found that his consulting company was recommending this XMLHttpRequest technology to lot of his client. He came up with a new name which he termed AJAX (asy...) Asynshronous means the browser isn’t hanging while its talking to server you can interact with the website while it is requesting data from server. XML is what is transferred between server and browser. Things changed a little bit in terms of it doesn’t have to be XML it can be HTML.
FLICKR: Yahoo’s flickr.com is a photo-organizing site that lets you “sort, store, search and share photos online.” Previously, flickr had used Flash as the main tool behind its photo display interface, but in May 2005 it announced that it was moving over to using Dynamic HTML and Ajax (http://blog.flickr .com/flickrblog/2005/05/from_flash_to_a.html). You have to sign up for an account to be able to see the tool in action, but because it’s free and photo manipulation tools on web applications are a great way of demonstrating Ajax techniques, you should look into it. Once you’ve logged in, you can access the tool via the Organize menu by selecting the Organize All Your Photos option (Figure 1-1). You can drag and drop photos into a single batch, and then you can rotate them and amend their tags. Upload a photo and see the status Google Suggest: Google Suggest is a version of a search engine that attempts to offer suggestions as you type other similar searches. Now this feature has been added to the basic google search engine Google Maps: Google Maps uses Ajax. When a location on the map is pinpointed it will load the relevant section of the map. If you then scroll along, rather than keeping the entire map in memory, it will load the map in blocks as and when you need them. Ajax Periodic Table: A periodic table which uses ajax to display data of each entry. This is not a very wide example but shows how ajax can be used to make things better
Instead of the traditional web application model where the browser itself is responsible for initiating requests to, and processing requests from, the web server, the Ajax model provides an intermediate layer— what Garrett calls an Ajax engine—to handle this communication. An Ajax engine is really just a JavaScript object or function that is called whenever information needs to be requested from the server. Instead of the traditional model of providing a link to another resource (such as another web page), each link makes a call to the Ajax engine, which schedules and executes the request. The request is done asynchronously, mean- ing that code execution doesn’t wait for a response before continuing. The server—which traditionally would serve up HTML, images, CSS, or JavaScript—is configured to return data that the Ajax engine can use. This data can be plain text, XML, or any other data format that you may need. The only requirement is that the Ajax engine can understand and interpret the data When the Ajax engine receives the server response, it goes into action, often parsing the data and making several changes to the user interface based on the information it was provided. Because this process involves transferring less information than the traditional web application model, user interface updates are faster, and the user is able to do his or her work more quickly.
In reality, all these technologies are available to be used in Ajax solutions, but only three are required: HTML/XHTML, DOM, and JavaScript. XHTML is obviously necessary for the displaying of informa- tion, while the DOM is necessary to change portions of an XHTML page without reloading it. The last part, JavaScript, is necessary to initiate the client-server communication and manipulate the DOM to update the web page. The other technologies in the list are helpful in fine-tuning an Ajax solution, but they aren’t necessary.
❑ Minimal traffic: Ajax applications should send and receive as little information as possible to and from the server. In short, Ajax can minimize the amount of traffic between the client and the server. Making sure that your Ajax application doesn’t send and receive unnecessary informa- tion adds to its robustness. ❑ No surprises: Ajax applications typically introduce different user interaction models than tradi- tional web applications. As opposed to the web standard of click-and-wait, some Ajax applica- tions use other user interface paradigms such as drag-and-drop or double-clicking. No matter what user interaction model you choose, be consistent so that the user knows what to do next. ❑ Established conventions: Don’t waste time inventing new user interaction models that your users will be unfamiliar with. Borrow heavily from traditional web applications and desktop applications, so there is a minimal learning curve. ❑ No distractions: Avoid unnecessary and distracting page elements such as looping animations and blinking page sections, marquee. Such gimmicks distract the user from what he or she is trying to accomplish. ❑ Accessibility: Consider who your primary and secondary users will be and how they most likely will access your Ajax application. Don’t program yourself into a corner so that an unex- pected new audience will be completely locked out. Will your users be using older browsers or special software? Make sure you know ahead of time and plan for it. ❑ Avoid entire page downloads: All server communication after the initial page download should be managed by the Ajax engine. Don’t ruin the user experience by downloading small amounts of data in one place but reloading the entire page in others. ❑ User first: Design the Ajax application with the users in mind before anything else. Try to make the common use cases easy to accomplish and don’t be caught up with how you’re going to fit in advertising or cool effects
Partial Page Updating You don’t have to update the data on an entire page. You can update only the portions of the page that require it. This should mean no full page refreshes, less data to be transferred, and an improved flow for the user experience. You don’t have to stutter from page to page. Invisible Data Retrieval The longer you look at a web page, the greater its chance to go out of date. With an Ajax application, even though on the surface the web page might not be told to do anything, it could be updating itself behind the scenes. Constant Updating Because you’re not waiting for a page refresh every time, and because Ajax can retrieve data under the covers, the web application can be constantly updated. A traditional software application such as Word or Outlook will alter the menus it displays or the views it shows, dependent on its configuration, or the data it holds or the situation or circumstances it finds itself in. It doesn’t have to wait for a server or user to perform an action before it can download new mail or apply a new template. Ajax techniques enable web applications to behave more like Windows applications because of this. Smooth Interfaces An interface that doesn’t have to be changed is almost inevitably a user interface that is easier to use. Ajax can cut both ways here in that you can use it to modify parts of the interface and simply confuse users by changing the ground beneath their feet. In theory, by making subtle alterations, you could aid the user’s passage through an interface or wizard and speed up the process. Simplicity and Rich Functionality As shown in the previous examples, some of the most impressive Ajax applications are those where you had to look for the Ajax functionality, such as Basecamp. If Ajax can be used to make your applications simpler while improving the user’s experience, then that must be an improvement. Drag and Drop Drag-and-drop functionality is one of the neatest features of most software applications, from Windows Explorer to Windows Desktop. It doesn’t strictly qualify as Ajax functionality. It’s something that’s been possible for a great many years in web applications, even before the introduction of the XMLHttp Request object. Most developers seem to opt for Flash or some similarly heavyweight solution rather than using the JavaScript and DOM solutions. In the reassessment of user-interface creation techniques that Ajax has introduced, drag-and-drop functionality can be used to manage front-end changes, and then these changes are submitted via Ajax to the server. For example, you drag several items on the screen into new positions, and then you log out. Later, when you come back, those items are located in the same positions. With such a host of benefits, it might be difficult to imagine why everyone isn’t switching over to using Ajax applications. There are definitely quite a few pitfalls, though, to consider.
The DOM is a representation of the web page as a hierarchy or tree structure, where every part of the page (the graphics, the text boxes, the buttons, and the text itself) is modeled by the browser. You can add items to the DOM or alter them using a scripting language (such as JavaScript or VBScript), and they will appear on the page immediately. They are typically addressed in the format that addresses the page in hierarchical format.
In order to understand exactly how Ajax concepts are put together, it is important to know how a web site processes a request and receives a response from a web server. The current standard that browsers use to acquire information from a web server is the HTTP. This is the means a web browser uses to send out a request from a web site and then receive a response from the web server that is currently in charge of returning the response. HTTP requests work somewhat like e-mail. That is to say that when a request is sent, certain headers are passed along that allow the web server to know exactly what it is to be serving and how to handle the request. While most headers are optional, there is one header that is absolutely required (provided you want more than just the default page on the server): the host header. This header is crucial in that it lets the server know what to serve up. Once a request has been received, the server then decides what response to return. There are many different response codes. Table above has a listing of some of the most common ones. It should be noted that there are various forms of request methods available. A few of them, like GET and POST.
Ajax is really just a concept used to describe the interaction of the client-side XMLHttpRequest object with server-based scripts. In order to make a request to the server through Ajax, an object must be created that can be used for different forms of functionality.
Once an instance of the XMLHttpRequest object has been created, there are a number of methods available to the user. abort() The abort method is really quite simple—it stops the request in its tracks. This function can be handy if you are concerned about the length of the connection. If you only want a request to fire for a certain length of time, you can call the abort method to stop the request prematurely. getAllResponseHeaders() You can use this method to obtain the full information on all HTTP headers that are being passed. An example set of headers might look like this: Date: Sun, 13 Nov 2005 22:53:06 GMT Server: Apache/2.0.53 (Win32) PHP/5.0.3 X-Powered-By: PHP/5.0.3 Content-Length: 527 Keep-Alive: timeout=15, max=98 Connection: Keep-Alive Content-Type: text/html getResponseHeader("headername") You can use this method to obtain the content of a particular piece of the header. This method can be useful to retrieve one part of the generally large string obtained from a set of headers. For example, to retrieve the size of the document requested, you could simply call getResponseHeader ("Content-Length"). open ("method","URL","async","username","pswd") Now, here is where we start to get into the meat and potatoes of the XMLHttpRequest object. This is the method you use to open a connection to a particular file on the server. It is where you pass in the method to open a file (GET or POST), as well as define how the file is to be opened. Keep in mind that not all of the arguments in this function are required and can be customized depending on the situation. setRequestHeader("label","value") With this method, you can give a header a label of sorts by passing in a string representing both the label and the value of said label. An important note is that this method may only be invoked after the open() method has been used, and must be used before the send function is called. send("content") This is the method that actually sends the request to the server. If the request was sent asynchronously, the response will come back immediately; if not, it will come back after the response is received. You can optionally specify an input string as an argument, which is helpful for processing forms, as it allows you to pass the values of form elements.
onreadystatechange The onreadystatechange property is an event handler that allows you to trigger certain blocks of code, or functions, when the state (referring to exactly where the process is at any given time) changes. For example, if you have a function that handles some form of initialization, you could get the main set of functionality you want to fire as soon as the state changes to the complete state. readyState The readyState property gives you an in-depth description of the part of the process that the current request is at. This is a highly useful property for exception handling, and can be important when deciding when to perform certain actions. You can use this property to create individual actions based upon how far along the request is. For example, you could have a set of code execute when readyState is loading, or stop executing when readyState is complete. responseText The responseText property will be returned once a request has gone through. If you are firing a request to a script of some sort, the output of the script will be returned through this property. With that in mind, most scripts will make use of this property by dumping it into an innerHTML property of an element, thereby asynchronously loading a script or document into a page element. responseXML This works similarly to responseText, but is ideal if you know for a fact that the response will be returned in XML format—especially if you plan to use built-in XML-handling browser functionality. status This property dictates the response code (a list of common response codes is shown in Table earlier) that was returned from the request. For instance, if the file requested could not be found, the status will be set to 404 because the file could not be found. statusText This property is merely a textual representation of the status property. Where the status property might be set to 404, the statusText would return Not Found. By using both the status and statusText properties together, you can give your user more in-depth knowl- edge of what has occurred. After all, not many users understand the significance of the number 404.
Internet Explorer implements XMLHttpRequest as an ActiveX object, and other browsers such as Firefox, Safari, and Opera implement it as a native JavaScript object. Because of these differences, the JavaScript code must contain logic to create an instance of XMLHttpRequest using the ActiveX technique or using the native JavaScript object technique. check the browser’s support of ActiveX objects. If the browser supports ActiveX objects, then you cre- ate the XMLHttpRequest object using ActiveX. Otherwise, you create it using the native JavaScript object technique.
First, you create a globally scoped variable named xmlHttp to hold the reference to the object. The createXMLHttpRequest method does the work of actually creating an instance of XMLHttpRequest. The method contains simple branching logic that determines how to go about creating the object. The call to window.ActiveXObject will return an object or null, which is evaluated by the if statement as true or false, thus indicating whether the browser supports ActiveX controls and thus is Internet Explorer5 or 6. If so, then the XMLHttpRequest object is created by instantiating a new instance of ActiveXObject, passing a string indicating the type of ActiveX object you want to create. In this instance, you provide Microsoft.XMLHTTP to the constructor, indicating your desire to create an instance of XMLHttpRequest. If the call to window.ActiveXObject fails, then the JavaScript branches to the else statement, which determines whether the browser implements XMLHttpRequest as a native JavaScript object. If window.XMLHttpRequest exists, then an instance of XMLHttpRequest is created. JavaScript’ s dynamically typed nature and that XMLHttpRequest implementations are compatible across various browsers, you can access the properties and methods of an instance of XMLHttpRequest identically, regardless of the method used to create the instance. This greatly simplifies the development process and keeps the JavaScript free of browser-specific logic.
If xhr was set then xhr will be XMLHttpRequest object. Anytime the state changes i.e. it goes from 0 to 1 to 2 to 3 to 4 we call showFunction We open a request with get method and call a file and true makes the call asynchronous. And finally send the request If xhr is not set we go in else part and display a message that XMLHttpRequest object cannot be created.
Check to see if readystate if it is 4 the request is finished being served. If status is 200 we came back from server with value of ok. We got the file responseText is a text which webserver pass back as response otherwise set a error message.
Poor Responsiveness Perhaps the most glaring problem noticed with Ajax is when it is used in theory to speed up the interac- tion, and it actually slows down the page. If you continually use Ajax to submit data to the server, then you could find that the page has slowed down. Alternately, if the server returns large datasets to the client, you can find that your browser will struggle to cope with the data in a timely manner. In theory, a search engine might seem like a good place to use Ajax to break up the data so that you don’t have to refresh the page when you move from pages 1–10 to pages 11–20. In reality, you’d still be much better off, though, using the server to slice the dataset up into small chunks, rather than getting the browser to attempt to deal with a 1,000-record-plus dataset. Intelligent and judicious applications of Ajax techniques are the key here. Breaks the Back Button on Your Browser Ajax applications can, if not judiciously applied, break the Back button on your browser. One of the prime examples of a great Ajax application, Gmail, uses the Back and Forward buttons very effectively. Also, there are plenty of web sites out there that don’t use Ajax techniques that disable the Back button anyway. In my list of crimes, this one doesn’t rate particularly highly. Breaking Bookmarks and Blocking Search Engine Indexes If you bookmark a page in an Ajax application, you could, of course, end up with a different page in your list of favorites. JavaScript creates a particular view of the page, and this “view” has no depen- dence on the original URL. Also, conversely, with a dynamic menu system, you might think you have shut off part of your site that is no longer accessible via the menu and regard it as defunct when, in fact, others can still access it. Plenty of sites have thousands of hits for old versions of pages that just cause errors on the server. It is possible to create web applications that handle bookmarks and Back buttons correctly. A good exam- ple of how to handle both effectively can be found at http://onjava.com/lpt/a/6293. Strain on the Browser If you push the entire burden for processing data back to the browser, you then become more reliant on the browser and the user’s machine to do the processing for you. Waiting for the browser to process a page is no better than waiting for a web server to get back to you with a response. In fact, in some cases, it could be worse if it is IE you’re waiting for and it decides to hog all of the processing space on your machine while it’s doing the processing and make the whole machine respond at a crawl.