Ajax (web technology): Difference between revisions

From Citizendium
Jump to navigation Jump to search
imported>Dhawal Sehgal
No edit summary
mNo edit summary
 
(116 intermediate revisions by 8 users not shown)
Line 1: Line 1:
{{EZarticle-open}}
{{subpages}}


AJAX - an acronym for '''Asynchronous JavaScript And XML''' - is an emerging web technology that enhances the end users' web browsing experience by streamlining background web content request, as opposed to generating and serving up new pages for every change or update to the web page.<br>
'''Asynchronous [[JavaScript]] and [[XML]] (AJAX)''' is a [[JavaScript]] programming technique that allows [[JavaScript]] running in a local [[web browser]] to fetch content from a [[web server]] ''in the background''.  The Javascript then places the newly fetched information into the web page without reloading the entire page.  Use of [[XHTML]] instead of the more relaxed [[HTML]] means that Javascript can use the standardized [[Document Object Model (XHTML)|XHTML DOM]] to correctly identify the sections of the web page to be updated.  Recent progress in [[JavaScript]] standards, and browser support of those standards, has made Ajax'd web pages more common. <i>The term Ajax (also written as '''AJAX''')</i> was coined by Jesse James Garrett in an article called "Ajax: A New Approach to Web Applications"<ref>{{citation
| first = Jesse James | last=Garrett
| url = http://adaptivepath.com/ideas/essays/archives/000385.php
| title = Ajax: A New Approach to Web Applications]
| journal = Adaptive Path}}</ref>
, who defines it as a combination of several technologies that come together in powerful ways to enhance the web browsing experience of the user.


In the article that coined the "Ajax" term, J.J. Garrett describes the technology as {{quotation|"An intermediary...between the user and the server."}}
The user interface improvement that an Ajax approach can bring is the reduction of the "refresh cycle" - pages do not need to be refreshed for each interaction, which enables designers to produce richer interfaces.


==Description==
To simplify the development of web sites and applications using the Ajax approach, many turn to a variety of [[JavaScript libraries]], like [[jQuery]], the [[Yahoo! UI Library]], [[Prototype (framework)|Prototype]] and [[Dojo (toolkit)|Dojo]]. Some back-end web frameworks also come with built-in techniques to make developing Ajax components easier - for instance, [[Ruby on Rails]] lets you create "partials" which can be called via XMLHttpRequest.


AJAX is not exactly a new programming language, but a new way to implement existing standards. It is essentially more than a single technology. It is a combination of various existing technologies which combine together in new, more powerful ways. <br>
Browsers implement Ajax in different ways. Most browsers do this by having a native XMLHttpRequest object, although one can simulate this object in older browsers using the XMLHTTP [[ActiveX]] object, or by using [[Flash]] or frames. The [[World Wide Web Consortium]] and the [[WHAT WG]] have been pushing for better standardization of XMLHttpRequest as part of the push towards [[HTML]] 5.
It has the aspects of: -<br>
• XHTML, CSS for standards-based presentation.<br>
• XML  and XSLT for data interchange and manipulation.<br>
XMLHttpRequest for asynchronous data retrieval.<br>
• Document Object Model for dynamic display and interaction.<br>
• JavaScript for binding everything together.<br>
<br>
The premise of AJAX is to allow light weight calls to a web server and update the web page currently displayed without re-rendering the entire page, but only the affected portion(s). <br>
The primary technological breakthrough that enabled AJAX is XmlHttpRequest (XHR), or XMLHTTP ActiveX object(an equivalent mechanism from Microsoft) in addition to [[JavaScript|JavaScript]] (older browsers may mimic AJAX's behavior with another technique using JavaScript and FRAMEs, known as Remote Scripting). XHR is a command that allows an application to request data using a script independently of when the user calls for a page refresh. Once the data is fetched, a JavaScript procedure can parse the data and update only the necessary part of the page that requires an update.<br>
There are many libraries that help in the development of AJAX enabled pages. For example, the Yahoo! UI Library, the Google Web Toolkit, or DoJo Toolkit, the ASP.NET AJAX Control toolkit. But in the end it all ultimately comes from XHR.<br>
AJAX has become so popular that is has forced some browsers to implement it natively, without use of COMs such as ActiveX and creating a standard built in object. <br>
AJAX is used to create better, faster, and more user-friendly web applications. Some even say that AJAX applications compete with desktop applications.


== Related standards ==
Ajax programming may require familiarity with a range of standards, including:
*<i>[[JavaScript]]</i>—A scripting language that is commonly hosted in a browser to add interactivity to HTML pages. Loosely resembling [[Java programming language]] in syntax, JavaScript is one of the more popular scripting language on the Web and is supported by all major browsers. Ajax applications are usually built in JavaScript.
*<i>[[Document Object Model (DOM)]]</i> —Defines the structure of a web page as a set of programmable objects that can be accessed through JavaScript. In Ajax programming, the DOM is leveraged to effectively redraw portions of the page.
*<i>[[Cascading Style Sheets]] (CSS) and [[Extensible Hypertext Markup Language]] ([[XHTML]])</i>— Provides a way to define the visual appearance based on industry standards. CSS is used in Ajax applications to modify the exterior of the user interface interactively.
*<i>[[XMLHttpRequest]]</i>—Allows a client-side script to perform an HTTP request. Ajax applications use the XMLHttpRequest object to perform asynchronous requests to the server as opposed to performing a full-page refresh or postback.


== Constituents ==
Although the Ajax acronym includes the word XML, it is important to note that Ajax calls do not necessarily use XML as the wire format (data encoding for the HTTP request and response).  The wire format could just as easily be [[JSON|JSON(JavaScript Object Notation)]], HTML, or plain text, depending on the situation. 


AJAX may include the use of a range of web technologies such as [[JavaScript|JavaScript]], [[XML:XML(eXtensible Mark Language)]], [[DOM:DOM(Document Object Model) ]], [[CSS CSS(Cascading Style Sheets)]], but does not necessarily mean they are necessary.
Despite its name, Ajax does not have to be asynchronous, and sometimes it is erroneously applied to be a simple function in a JavaScript library.  An "Ajax" call to a web server is usually an asynchronous (non-blocking) call; thus, a [[callback function]] must be specified which will execute when the web server responds.


An odd fact is that none of the technologies mentioned above are mandatory to create an AJAX page or at least an AJAX like functionality. For instance, one could use an inline frame that contains a document that uses META Refresh to poll and update content on a portion of the inline frame's parent element.  XML is just one of the formats the response can be sent and in many cases [[JSON JSON(JavaScript Object Notation]] is often an easier and better choice and raw HTML or plain text can be sent as well.  Despite its name, AJAX does not have to be asynchronous, and sometimes it is erroneously applied to be a simple function in a JavaScript library.
Except perhaps for Javascript,the above mentioned technologies are not mandatory for creating an Ajax-like functionality. For instance, one could use an [[IFrame]] that contains a document that uses META Refresh to poll and update content on a portion of the IFrame's parent element.


== Benefits ==
==What makes Ajax different?==
{{Image|AjaxAppModel.JPG|right|450px| Difference between the classical web application model and the Ajax web application model}}


AJAX has come a long way since the time it was introduced. It has become so popular because of the benefits it has over the traditional page wise style of website creation. Some of its major benefits are: -
In the classical web application model, the user makes an [[http]] (hyper text transfer protocol) request to a server using a browser. The server receives the user's request and takes the appropriate actions - interacting with the data stores, doing back end processing, talking to various legacy systems etc. The content thus generated is sent to the user (in [[HTML]]) as the response. This is how the basic<i> [[Client-Server Model]] </i>works on the web.
*AJAX helps in improving user interactivity with the application interface.
This model makes a lot of technical sense, but it is not that great for the user. This is because after a user makes a request to the server, he had to wait till the time the server finishes the required processing and sends an HTML page as the response.
*AJAX can buffer data before the user actually needs it. This helps in increasing the overall speed of the web application and reduces wait time for the user.
 
An Ajax application is different from the tradtional page based web application as Ajax introduces an intermediary between the user and the server - <i>An Ajax engine</i>, which eliminates the start-stop-start-stop nature of client-server interaction. When a web page loads and a new session starts, the browser loads and Ajax engine (written in [[JavaScript]] and residing in a hidden frame). This engine becomes responsible for what the user sees and what is sent to the server on behalf of the user. The Ajax engine allows the asynchronous interaction of the user with the web application (independent of the communication with the server). Thus, the user does not have to wait for the server to process any request. The user can actively interact with the web application after making request(s), while the server does the required processing in the back.
 
== Critique ==
 
=== Benefits ===
Ajax has come a long way since the time it was introduced. It has become so popular because of the benefits it has over the traditional page wise style of website creation. Some of its major benefits are:
*Ajax helps in improving user interactivity with the application interface.
*Ajax can buffer data before the user actually needs it. This helps in increasing the overall speed of the web application and reduces wait time for the user.
*Helps in reducing bandwidth requirements for an application as only the data that is needed is requested and transferred – refreshing the entire page is not necessary.
*Helps in reducing bandwidth requirements for an application as only the data that is needed is requested and transferred – refreshing the entire page is not necessary.
*AJAX helps in executing queries that take a long time to run. Instead of waiting for the results after clicking the submit button, AJAX can make the data request in the background, while the user can still continually interact with the page.<br>
*Ajax helps in executing queries that take a long time to run. Instead of waiting for the results after clicking the submit button, Ajax can make the data request in the background, while the user can still continually interact with the page.<br>
*Dynamic data filtering works well with AJAX. An example of the same is the Cascading dropdown control of the ASP.NET AJAX control toolkit.
*Dynamic data filtering works well with Ajax. An example of the same is the Cascading dropdown control of the ASP.NET Ajax control toolkit.
*AJAX is really good for form submissions. Feedback can be given to a user as the form is filled. There is no need to wait for the form to be submitted. For example, Hints can be given to a user while he is filling a form.
*Ajax is really good for form submissions. Feedback can be given to a user as the form is filled. There is no need to wait for the form to be submitted. For example, Hints can be given to a user while he is filling a form.
*Programmers can use a number of different languages or formats to develop Ajax pages for their specific goal(s). For example, raw data (usually obtained in [[XML]]) from a server-side database is separated from the format or structure of the webpage (which is usually structured in [[XHTML]]). Dynamic handling of DOM can be enabled. CSS use allows for the separating of style elements on the page, like fonts and picture placement.
*Ajax also separates the functionality of web pages by combining different elements in different ways. For example, JavaScript on the client-side browser is combined with XMLHttp to enable communication between client and server browsers. Then any server-side program or scripting language allows the programmer to quickly respond to client requests in a language and format they are familiar with
*There are a lot of [[AJAX framework|Ajax frameworks]] available for developers to choose from.
 
=== Drawbacks ===
In addition to the benefits, Ajax has some drawbacks as well:
*Because the data and format in Ajax pages needs to be so specific, the web page cannot connect with the browser history engine. This results in inconveniences and delays in searching
*This lack of browser integration leads to an abnormal behavior of the "Back" button(or an equivalent scripting command). Pressing the back button takes the user to the previous page (as the entire Ajax application run on a single page) —which is completely outside of the given application.
*A similar problem exists with bookmarks. When a user tries to bookmark an Ajax page, only the address of the application is bookmarked; the state of the given application is not bookmarked.
*Last but not the least, if Ajax is not implemented properly – it can degrade the user performance instead of improving it.
*There might be a lag, for example, when the web page interface loads because of pre-loaded data and having to handle request objects properly.
*Websites that use Ajax must also take care to link their information to a public URL because some search engines aren’t equipped for Ajax. This stems from another Ajax disadvantage.
*The reliance of Ajax on JavaScript (which isn’t used by some search engines) means that web sites constructed through Ajax should be tested on several browsers for compatibility. This is because JavaScript can be installed differently on different browsers. Its ability for customization can also make it incompatible with other browsers.
 
== Applications of Ajax on the Web ==
The popularity of Ajax has become enormous since the time it was introduced. This is clear by the number of Ajax-based web applications that have crawled on to the [[World Wide Web]].
*Google is using the Ajax approach to develop many of its applications including [[Gmail]], [[Orkut]], [[Google Maps]], [[Google Suggest]], [[Google Groups]].
*Many features of ''Flickr'' depend on Ajax.
*Amazon’s search engine <i>A9.com</i> applies similar techniques.
*Facebook has been using Ajax since a long time.
*Online documentation and presentation tools such as [[Google Docs]], 280sildes.com are a great application of Ajax on the web.
 
The web applications described in this section demonstrate that Ajax is practical for real-world applications, in addition to being technically sound. Ajax applications can be any size - from the very simple, single-function Google Suggest; to the very complex and sophisticated Google Maps.
 
===Gmail===
Gmail was one of the first mainstream applications to use Ajax (even though the term had not been coined by then).The many features of Gmail that make use of Ajax include:
*Searching emails without page reload
*Reading emails without page reload
*Spelling checker
*Starring/Tagging emails without page reload
*Ability to check for new emails on a regular basis
*Automatic saving of drafts
*Status messages.
*Built-in Google Chat application.
*Dynamic update of Google Chat status
 
===Facebook===
[[Facebook]] Ajaxed their website in a number of ways. Then number of ajaxed features on facebook has increased rapidly since the time it was first implemented. Some features of facebook that include Ajax are as follows: -
*Friends can be addes/confirmed without page reload - this was one of the first features of facebook to be implemented in Ajax.
*Replying to messages without reloading the page.
*The newer feature of online chat and popup for new notifications is an application of Ajax.
*The Inbox counter gets updated automatically without page reload.
 
==Implementation Example of Ajax==
 
===Ajax implementation using XMLHttpRequest===
 
The XMLHttpRequest object provides the most complete option for making Ajax calls.It is not supported by all browsers.Older versions of Safari and Opera do not have XMLHttpRequest support.[[ActiveX]] must be enabled in IE 5 and 6.
 
The XMLHttpRequest class is a generic [[HTTP]] client for [[JavaScript]],originally designed by Microsoft to allow [[Internet Explorer]] to load [[XML]] documents from JavaScript(in IE, XMLHttpRequest is an [[ActiveX]] object).The method allows for JavaScript to make GET and POST HTTP requests.Synchronous as well as asynchronous forms of communication are possible.Due to security restrictions HTTP(S) requests can only be made to the same domain as the currently loaded page.Although a limitation,it not only enhances security but also provides a simpler programming model.This lets JavaScript code implicitly trust any data it loads from XMLHttpRequest.


== Drawbacks ==
An object is declared using the ''new XMLHttpRequest()'' call.In IE an ActiveX object needs to be declared( ''new ActiveXObject("MSXML2.XMLHTTP.3.0")'').


In addition to the benefits, AJAX has some drawbacks as well: -
The main methods associated with this object include:
*The foremost drawback of AJAX is that the browser's "back" button (or equivalent scripting command) does not behave as expected with a traditional page-driven application. Pressing the back button takes the user to the previous page (as AJAX application run on a single page) —which is completely outside of the given application.
*'''open():'''Lets you set the type of request(GET/POST/PUT/PROPFIND),the [[URL]],mode(Synchronous/Asynchronous).Optional parameters(Username/Password) for HTTP authentication can also be passed.
*A similar problem exists with bookmarks. When a user tries to bookmark an AJAX page, only the address of the application is bookmarked; the state of the given application is not bookmarked.
       
*Last but not the least, if AJAX is not implemented properly – it can degrade the user performance instead of improving it.
        open(type,isAsync,username,password)


== AJAX Application on the Web ==
*'''send():'''Lets you make the connection with the URL specified in open.For a synchronous request it will be a blocking call.Otherwise it will return immediately.For a POST request the payload is passed as a parameter(NULL for GET).


*Google is using the AJAX approach to develop many of its applications. All of the major products introduced by Google over the last few years – [[Gmail]], [[Orkut]], [[Google maps]], [[Google suggest]], [[Google Groups]] – are AJAX applications.
        send(payload)
*Many features of Flicker depend on AJAX
Other methods like serRequestHeader,getResponseHeader,abort are also quite useful.Some methods are browser specific.
*Amazon’s search engine A9.com applies similar techniques.
These projects demonstrate that AJAX is practical for real-world applications, in addition to being technically sound.
Also, Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.<br>
By seeing these applications, it can be said that AJAX is not a technology that works only in the laboratory, it has a lot more to it.


== Examples of AJAX Frameworks ==
XMLHttpRequest also provides a number of properties like status,statusText,readyState etc.[[Mozilla Firefox]] provides event handlers like onerror,onprogress and onload.


*Microsoft .NET (Visual Studio)
An example JavaScript code which uses open to set up a synchronous GET request to index.html:
*Google Web Toolkit
  var request=new XMLHttpRequest();      //Object Declaration
*Ruby on Rails (ROR)
  request.open('GET','index.html',false); //False means it is not asynchronous
*Echo
  request.send(null);                    //Payload is Null for GET
  if(request.status==401)               
    alert('Access denied');
  else
    alert(request.responseText);          //The responseText is String type


== References ==
== References ==
*Fresh: nuts and bolts: What does AJAX mean for you? By, Daniel F. Zucker
{{reflist | 2}}[[Category:Suggestion Bot Tag]]
*Ajax: A New Approach to Web Applications. By, Jesse James Garrett

Latest revision as of 16:00, 7 July 2024

This article is developing and not approved.
Main Article
Discussion
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
 
This editable Main Article is under development and subject to a disclaimer.

Asynchronous JavaScript and XML (AJAX) is a JavaScript programming technique that allows JavaScript running in a local web browser to fetch content from a web server in the background. The Javascript then places the newly fetched information into the web page without reloading the entire page. Use of XHTML instead of the more relaxed HTML means that Javascript can use the standardized XHTML DOM to correctly identify the sections of the web page to be updated. Recent progress in JavaScript standards, and browser support of those standards, has made Ajax'd web pages more common. The term Ajax (also written as AJAX) was coined by Jesse James Garrett in an article called "Ajax: A New Approach to Web Applications"[1] , who defines it as a combination of several technologies that come together in powerful ways to enhance the web browsing experience of the user.

The user interface improvement that an Ajax approach can bring is the reduction of the "refresh cycle" - pages do not need to be refreshed for each interaction, which enables designers to produce richer interfaces.

To simplify the development of web sites and applications using the Ajax approach, many turn to a variety of JavaScript libraries, like jQuery, the Yahoo! UI Library, Prototype and Dojo. Some back-end web frameworks also come with built-in techniques to make developing Ajax components easier - for instance, Ruby on Rails lets you create "partials" which can be called via XMLHttpRequest.

Browsers implement Ajax in different ways. Most browsers do this by having a native XMLHttpRequest object, although one can simulate this object in older browsers using the XMLHTTP ActiveX object, or by using Flash or frames. The World Wide Web Consortium and the WHAT WG have been pushing for better standardization of XMLHttpRequest as part of the push towards HTML 5.

Related standards

Ajax programming may require familiarity with a range of standards, including:

  • JavaScript—A scripting language that is commonly hosted in a browser to add interactivity to HTML pages. Loosely resembling Java programming language in syntax, JavaScript is one of the more popular scripting language on the Web and is supported by all major browsers. Ajax applications are usually built in JavaScript.
  • Document Object Model (DOM) —Defines the structure of a web page as a set of programmable objects that can be accessed through JavaScript. In Ajax programming, the DOM is leveraged to effectively redraw portions of the page.
  • Cascading Style Sheets (CSS) and Extensible Hypertext Markup Language (XHTML)— Provides a way to define the visual appearance based on industry standards. CSS is used in Ajax applications to modify the exterior of the user interface interactively.
  • XMLHttpRequest—Allows a client-side script to perform an HTTP request. Ajax applications use the XMLHttpRequest object to perform asynchronous requests to the server as opposed to performing a full-page refresh or postback.

Although the Ajax acronym includes the word XML, it is important to note that Ajax calls do not necessarily use XML as the wire format (data encoding for the HTTP request and response). The wire format could just as easily be JSON(JavaScript Object Notation), HTML, or plain text, depending on the situation.

Despite its name, Ajax does not have to be asynchronous, and sometimes it is erroneously applied to be a simple function in a JavaScript library. An "Ajax" call to a web server is usually an asynchronous (non-blocking) call; thus, a callback function must be specified which will execute when the web server responds.

Except perhaps for Javascript,the above mentioned technologies are not mandatory for creating an Ajax-like functionality. For instance, one could use an IFrame that contains a document that uses META Refresh to poll and update content on a portion of the IFrame's parent element.

What makes Ajax different?

Difference between the classical web application model and the Ajax web application model

In the classical web application model, the user makes an http (hyper text transfer protocol) request to a server using a browser. The server receives the user's request and takes the appropriate actions - interacting with the data stores, doing back end processing, talking to various legacy systems etc. The content thus generated is sent to the user (in HTML) as the response. This is how the basic Client-Server Model works on the web. This model makes a lot of technical sense, but it is not that great for the user. This is because after a user makes a request to the server, he had to wait till the time the server finishes the required processing and sends an HTML page as the response.

An Ajax application is different from the tradtional page based web application as Ajax introduces an intermediary between the user and the server - An Ajax engine, which eliminates the start-stop-start-stop nature of client-server interaction. When a web page loads and a new session starts, the browser loads and Ajax engine (written in JavaScript and residing in a hidden frame). This engine becomes responsible for what the user sees and what is sent to the server on behalf of the user. The Ajax engine allows the asynchronous interaction of the user with the web application (independent of the communication with the server). Thus, the user does not have to wait for the server to process any request. The user can actively interact with the web application after making request(s), while the server does the required processing in the back.

Critique

Benefits

Ajax has come a long way since the time it was introduced. It has become so popular because of the benefits it has over the traditional page wise style of website creation. Some of its major benefits are:

  • Ajax helps in improving user interactivity with the application interface.
  • Ajax can buffer data before the user actually needs it. This helps in increasing the overall speed of the web application and reduces wait time for the user.
  • Helps in reducing bandwidth requirements for an application as only the data that is needed is requested and transferred – refreshing the entire page is not necessary.
  • Ajax helps in executing queries that take a long time to run. Instead of waiting for the results after clicking the submit button, Ajax can make the data request in the background, while the user can still continually interact with the page.
  • Dynamic data filtering works well with Ajax. An example of the same is the Cascading dropdown control of the ASP.NET Ajax control toolkit.
  • Ajax is really good for form submissions. Feedback can be given to a user as the form is filled. There is no need to wait for the form to be submitted. For example, Hints can be given to a user while he is filling a form.
  • Programmers can use a number of different languages or formats to develop Ajax pages for their specific goal(s). For example, raw data (usually obtained in XML) from a server-side database is separated from the format or structure of the webpage (which is usually structured in XHTML). Dynamic handling of DOM can be enabled. CSS use allows for the separating of style elements on the page, like fonts and picture placement.
  • Ajax also separates the functionality of web pages by combining different elements in different ways. For example, JavaScript on the client-side browser is combined with XMLHttp to enable communication between client and server browsers. Then any server-side program or scripting language allows the programmer to quickly respond to client requests in a language and format they are familiar with
  • There are a lot of Ajax frameworks available for developers to choose from.

Drawbacks

In addition to the benefits, Ajax has some drawbacks as well:

  • Because the data and format in Ajax pages needs to be so specific, the web page cannot connect with the browser history engine. This results in inconveniences and delays in searching
  • This lack of browser integration leads to an abnormal behavior of the "Back" button(or an equivalent scripting command). Pressing the back button takes the user to the previous page (as the entire Ajax application run on a single page) —which is completely outside of the given application.
  • A similar problem exists with bookmarks. When a user tries to bookmark an Ajax page, only the address of the application is bookmarked; the state of the given application is not bookmarked.
  • Last but not the least, if Ajax is not implemented properly – it can degrade the user performance instead of improving it.
  • There might be a lag, for example, when the web page interface loads because of pre-loaded data and having to handle request objects properly.
  • Websites that use Ajax must also take care to link their information to a public URL because some search engines aren’t equipped for Ajax. This stems from another Ajax disadvantage.
  • The reliance of Ajax on JavaScript (which isn’t used by some search engines) means that web sites constructed through Ajax should be tested on several browsers for compatibility. This is because JavaScript can be installed differently on different browsers. Its ability for customization can also make it incompatible with other browsers.

Applications of Ajax on the Web

The popularity of Ajax has become enormous since the time it was introduced. This is clear by the number of Ajax-based web applications that have crawled on to the World Wide Web.

  • Google is using the Ajax approach to develop many of its applications including Gmail, Orkut, Google Maps, Google Suggest, Google Groups.
  • Many features of Flickr depend on Ajax.
  • Amazon’s search engine A9.com applies similar techniques.
  • Facebook has been using Ajax since a long time.
  • Online documentation and presentation tools such as Google Docs, 280sildes.com are a great application of Ajax on the web.

The web applications described in this section demonstrate that Ajax is practical for real-world applications, in addition to being technically sound. Ajax applications can be any size - from the very simple, single-function Google Suggest; to the very complex and sophisticated Google Maps.

Gmail

Gmail was one of the first mainstream applications to use Ajax (even though the term had not been coined by then).The many features of Gmail that make use of Ajax include:

  • Searching emails without page reload
  • Reading emails without page reload
  • Spelling checker
  • Starring/Tagging emails without page reload
  • Ability to check for new emails on a regular basis
  • Automatic saving of drafts
  • Status messages.
  • Built-in Google Chat application.
  • Dynamic update of Google Chat status

Facebook

Facebook Ajaxed their website in a number of ways. Then number of ajaxed features on facebook has increased rapidly since the time it was first implemented. Some features of facebook that include Ajax are as follows: -

  • Friends can be addes/confirmed without page reload - this was one of the first features of facebook to be implemented in Ajax.
  • Replying to messages without reloading the page.
  • The newer feature of online chat and popup for new notifications is an application of Ajax.
  • The Inbox counter gets updated automatically without page reload.

Implementation Example of Ajax

Ajax implementation using XMLHttpRequest

The XMLHttpRequest object provides the most complete option for making Ajax calls.It is not supported by all browsers.Older versions of Safari and Opera do not have XMLHttpRequest support.ActiveX must be enabled in IE 5 and 6.

The XMLHttpRequest class is a generic HTTP client for JavaScript,originally designed by Microsoft to allow Internet Explorer to load XML documents from JavaScript(in IE, XMLHttpRequest is an ActiveX object).The method allows for JavaScript to make GET and POST HTTP requests.Synchronous as well as asynchronous forms of communication are possible.Due to security restrictions HTTP(S) requests can only be made to the same domain as the currently loaded page.Although a limitation,it not only enhances security but also provides a simpler programming model.This lets JavaScript code implicitly trust any data it loads from XMLHttpRequest.

An object is declared using the new XMLHttpRequest() call.In IE an ActiveX object needs to be declared( new ActiveXObject("MSXML2.XMLHTTP.3.0")).

The main methods associated with this object include:

  • open():Lets you set the type of request(GET/POST/PUT/PROPFIND),the URL,mode(Synchronous/Asynchronous).Optional parameters(Username/Password) for HTTP authentication can also be passed.
        open(type,isAsync,username,password)
  • send():Lets you make the connection with the URL specified in open.For a synchronous request it will be a blocking call.Otherwise it will return immediately.For a POST request the payload is passed as a parameter(NULL for GET).
        send(payload)

Other methods like serRequestHeader,getResponseHeader,abort are also quite useful.Some methods are browser specific.

XMLHttpRequest also provides a number of properties like status,statusText,readyState etc.Mozilla Firefox provides event handlers like onerror,onprogress and onload.

An example JavaScript code which uses open to set up a synchronous GET request to index.html:

  var request=new XMLHttpRequest();       //Object Declaration
  request.open('GET','index.html',false); //False means it is not asynchronous
  request.send(null);                     //Payload is Null for GET
  if(request.status==401)                 
    alert('Access denied');
  else
    alert(request.responseText);          //The responseText is String type

References

  1. Garrett, Jesse James, "Ajax: A New Approach to Web Applications]", Adaptive Path