SlideShare a Scribd company logo
1 of 32
Download to read offline
Web development



                                                          Client-side programming

                                                         Rich Internet Applications
                                                                 and AJAX




/home/corno/Mirror/elite/slide/Computers/Programming/Languages/JavaScript/AJAX/ajax_v1.odp
Rich Internet Application
Rich Internet applications (RIA) are web
applications that have the features and
functionality of traditional desktop
applications.
RIAs typically
  transfer the processing necessary for the user
  interface to the web client
  keep the bulk of the data (i.e., maintaining the
  state of the program, the data etc) back on the
  application server.
Main goals of RIAs
Most sophisticated RIAs exhibit a look and
feel approaching a desktop environment.
  Richer. User-interface behaviors not obtainable
  using only the HTML widgets available to
  standard browser-based Web applications: drag
  and drop, using a slider to change data,
  calculations performed by the client and which
  do not need to be sent back to the server, ...
  More responsive. The interface behaviors are
  typically much more responsive than those of a
  standard Web browser that must always interact
  with a remote server.
Performance of RIAs
Client/Server balance. The demand for
client and server computing resources is
better balanced. This frees server resources,
allowing the same server hardware to handle
more client sessions concurrently.
Performance of RIAs
Asynchronous communication. The client
engine can interact with the server without
waiting for the user to perform an interface
action such as clicking on a button or link.
This allows the user to view and interact with
the page asynchronously from the client
engine's communication with the server.
  Example: prefetching (an application anticipates
  a future need for certain data, and downloads it
  to the client before the user requests it)
Performance or RIAs
Network efficiency. Network traffic may be
significantly reduced because an application-
specific client engine can be more intelligent
than a Web browser when deciding what
data needs to be exchanged with servers.
  Less data is being transferred for each
  interaction, and overall network load is reduced.
  However, use of asynchronous prefetching
  techniques can neutralize or even reverse this
  potential benefit.
AJAX definition
Asynchronous JavaScript And XML.
AJAX is a type of programming made
popular in 2005 by Google (with Google
Suggest).
AJAX is not a new programming language,
but a new way to use existing standards.
With AJAX you can create better, faster, and
more user-friendly web applications.
AJAX is based on JavaScript and HTTP
requests.
Key enabling technology
With AJAX, your JavaScript can
communicate directly with the server, using
the JavaScript XMLHttpRequest object.
By using the XMLHttpRequest object, a web
developer can update a page with data from
the server -- after the page has loaded!
The XMLHttpRequest object is supported in
Internet Explorer 5.0+, Safari 1.2, Mozilla
1.0 / Firefox, Opera 8+, and Netscape 7.
http://www.w3.org/TR/XMLHttpRequest/
XMLHttpRequest – the name
The name of the object is wrong, but
maintained for historical reasons:
  May receive any text-based content, not just
  XML
  May use also HTTPS, not just HTTP protocol
  May handle both Requests and Responses, of
  all HTTP methods
Standard definition
interface XMLHttpRequest {
  // event handler
           attribute EventListener onreadystatechange;
  // state
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;
  readonly attribute unsigned short readyState;
Standard definition
  // request
  void open(in DOMString method, in DOMString url);
  void open(in DOMString method, in DOMString url, in boolean async);
  void open(in DOMString method, in DOMString url, in boolean async, in
DOMString user);
  void open(in DOMString method, in DOMString url, in boolean async, in
DOMString user, in DOMString password);
  void setRequestHeader(in DOMString header, in DOMString value);
  void send();
  void send(in DOMString data);
  void send(in Document data);
  void abort();
Standard definition
     // response
     DOMString getAllResponseHeaders();
     DOMString getResponseHeader(in DOMString header);
     readonly attribute DOMString responseText;
     readonly attribute Document responseXML;
     readonly attribute unsigned short status;
     readonly attribute DOMString statusText;
};
Request states
UNSENT = 0
 The request is not initialized
OPENED = 1
 The request has been set up
HEADERS_RECEIVED = 2
 The request has been sent
LOADING = 3
 The request is in process
DONE = 4
 The request is complete
State transition diagram
                       .setRequestHeader()
new
                              OPENED                  OPENED
      UNSENT     .open()
                              not sent                  sent
                                         .send()
                                                            .send()

          Connection closed                   All headers
                                              received
 DONE       DONE
                             LOADING
  error    not error
                                                    HEADERS
                                    (partial) body _RECEIVED
             Connection closed      received
XMLHttpRequest properties
onreadystatechange
  stores the function that will process the
  response from a server
  xmlHttp.onreadystatechange =
  function() { ... }
readyState
  holds the status of the server’s response. Each
  time readyState changes, the
  onreadystatechange function will be executed.
responseText
  the data sent back from the server can be
  retrieved with the responseText property
Methods
open(method, url, async, user, password)
  method = “GET”, “POST”
  url = complete URL to request
  async = true/false (optional, default=true)
  user, password (optional)
  Interrupts any on-going send()
setRequestHeader(header, value)
  Adds a new header to the HTTP Request
  Content-Type is one common header to send
    Examples: text/xml, application/xml
Methods
send(data)
  Initiates the request
  data = HTTP request body (optional)
    May be a Document or DOMString
  The URL was already given in open()
  send() terminates immediately if async==true,
  but transfer continues in the background
    Generates readystatechange events
  send() transfers data synchronously if
  async==false
Methods
getAllResponseHeaders()
  Return all response headers as a single string,
  with headers separated by CR+LF
  Invalid if UNSENT or OPENED
getResponseHeader(header)
  Returns the value of a single header
  Invalid if UNSENT or OPENED
Receiving the response body
responseText of type DOMString
  If LOADING (partial body) or DONE
  Allow access to a “raw string” of the response
  body
responseXML of type Document
  Only if DONE
  For text/xml (or application/xml or *+xml) content
  types, otherwise null
  Allows access to the DOM of the XML document
Example
Create a standard HTML form with two text
fields: username and time.
The username field will be filled in by the
user and the time field will be filled in using
AJAX.
No submit button is needed.
Example

<html>
<body> <form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form> </body>
</html>
Creating an XMLHttpRequest
 object
<script type="text/javascript">
function ajaxFunction()
{
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();

  ...
}
</script>
Supporting all browsers
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e) {
  // Internet Explorer
  try { // Internet Explorer 6.0+
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e) {
    try { // Internet Explorer 5.5+
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e) {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
}
</script>
Calling the server
xmlHttp.open("GET","time.jsp",true);
xmlHttp.send(null);
Processing the response

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
  {
  // Get the data from the server's response
  document.myForm.time.value=xmlHttp.responseText;
  }
}
Attaching to an event

<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" /
>
Time: <input type="text" name="time" />
</form>
Complete example
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
  var xmlHttp=new XMLHttpRequest();

 xmlHttp.onreadystatechange=function()
   {
   if(xmlHttp.readyState==4)
     {
     document.myForm.time.value=xmlHttp.responseText;
     }
   }

  xmlHttp.open("GET","time.asp",true);
  xmlHttp.send(null);
  }
</script>
<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form> </body>
</html>
AJAX architecture
AJAX
behavior
Exercise 1
Create an auto-complete feature for entering
the name in a FORM
For every typed letter, an associated text
must be updated, reflecting the list of all
possible names with those initial(s)
Once submitted, the name adds up to the list
Clicking on the suggestion auto-fills the box

Name Jo               Suggestions: Joe, Joseph, John

      SUBMIT
Exercise 2
Create a FORM for entering the name of a
city, based on two drop-down menus
(<select> tags).
  The first <select> contains the list of all
  provinces (AO, BO, CN, MI, TO, ...)
  The second <select> contains the list of all cities
  in the province
Every time the user changes the province,
then the list of cities MUST be updated
The form may be submitted only if
information is complete
References
http://en.wikipedia.org/wiki/Rich_Internet_Ap
plications
http://en.wikipedia.org/wiki/AJAX
http://www.w3schools.com/ajax/
http://www.w3.org/TR/XMLHttpRequest/

More Related Content

What's hot

Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 

What's hot (20)

Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Interoperable Web Services with JAX-WS and WSIT
Interoperable Web Services with JAX-WS and WSITInteroperable Web Services with JAX-WS and WSIT
Interoperable Web Services with JAX-WS and WSIT
 
Interoperable Web Services with JAX-WS
Interoperable Web Services with JAX-WSInteroperable Web Services with JAX-WS
Interoperable Web Services with JAX-WS
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State Management
 
Ajax
AjaxAjax
Ajax
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
M Ramya
M RamyaM Ramya
M Ramya
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
SERVIET
SERVIETSERVIET
SERVIET
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Library Project
Library ProjectLibrary Project
Library Project
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 

Viewers also liked

Viewers also liked (17)

Search and Optimization Strategies
Search and Optimization StrategiesSearch and Optimization Strategies
Search and Optimization Strategies
 
Ausili definizioni e normative
Ausili definizioni e normativeAusili definizioni e normative
Ausili definizioni e normative
 
Accessibilità dei siti web
Accessibilità dei siti webAccessibilità dei siti web
Accessibilità dei siti web
 
Presentazione Servizio Poli@Home
Presentazione Servizio Poli@HomePresentazione Servizio Poli@Home
Presentazione Servizio Poli@Home
 
Web Accessibility
Web AccessibilityWeb Accessibility
Web Accessibility
 
Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)
 
Logic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic WebLogic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic Web
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
Linked Data for Ambient Intelligence
Linked Data for Ambient IntelligenceLinked Data for Ambient Intelligence
Linked Data for Ambient Intelligence
 
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Computational complexity
Computational complexityComputational complexity
Computational complexity
 
Web Transactions
Web TransactionsWeb Transactions
Web Transactions
 
Lucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in CLucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in C
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP library
 
Introduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization SystemIntroduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization System
 
Semantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, OntologiesSemantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, Ontologies
 

Similar to Introduction to Ajax programming

AJAX
AJAXAJAX
AJAX
ARJUN
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
dominion
 

Similar to Introduction to Ajax programming (20)

Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax
AjaxAjax
Ajax
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
AJAX
AJAXAJAX
AJAX
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Mashup
MashupMashup
Mashup
 
Ajax
AjaxAjax
Ajax
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Recently uploaded (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

Introduction to Ajax programming

  • 1. Web development Client-side programming Rich Internet Applications and AJAX /home/corno/Mirror/elite/slide/Computers/Programming/Languages/JavaScript/AJAX/ajax_v1.odp
  • 2. Rich Internet Application Rich Internet applications (RIA) are web applications that have the features and functionality of traditional desktop applications. RIAs typically transfer the processing necessary for the user interface to the web client keep the bulk of the data (i.e., maintaining the state of the program, the data etc) back on the application server.
  • 3. Main goals of RIAs Most sophisticated RIAs exhibit a look and feel approaching a desktop environment. Richer. User-interface behaviors not obtainable using only the HTML widgets available to standard browser-based Web applications: drag and drop, using a slider to change data, calculations performed by the client and which do not need to be sent back to the server, ... More responsive. The interface behaviors are typically much more responsive than those of a standard Web browser that must always interact with a remote server.
  • 4. Performance of RIAs Client/Server balance. The demand for client and server computing resources is better balanced. This frees server resources, allowing the same server hardware to handle more client sessions concurrently.
  • 5. Performance of RIAs Asynchronous communication. The client engine can interact with the server without waiting for the user to perform an interface action such as clicking on a button or link. This allows the user to view and interact with the page asynchronously from the client engine's communication with the server. Example: prefetching (an application anticipates a future need for certain data, and downloads it to the client before the user requests it)
  • 6. Performance or RIAs Network efficiency. Network traffic may be significantly reduced because an application- specific client engine can be more intelligent than a Web browser when deciding what data needs to be exchanged with servers. Less data is being transferred for each interaction, and overall network load is reduced. However, use of asynchronous prefetching techniques can neutralize or even reverse this potential benefit.
  • 7. AJAX definition Asynchronous JavaScript And XML. AJAX is a type of programming made popular in 2005 by Google (with Google Suggest). AJAX is not a new programming language, but a new way to use existing standards. With AJAX you can create better, faster, and more user-friendly web applications. AJAX is based on JavaScript and HTTP requests.
  • 8. Key enabling technology With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. By using the XMLHttpRequest object, a web developer can update a page with data from the server -- after the page has loaded! The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. http://www.w3.org/TR/XMLHttpRequest/
  • 9. XMLHttpRequest – the name The name of the object is wrong, but maintained for historical reasons: May receive any text-based content, not just XML May use also HTTPS, not just HTTP protocol May handle both Requests and Responses, of all HTTP methods
  • 10. Standard definition interface XMLHttpRequest { // event handler attribute EventListener onreadystatechange; // state const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; const unsigned short LOADING = 3; const unsigned short DONE = 4; readonly attribute unsigned short readyState;
  • 11. Standard definition // request void open(in DOMString method, in DOMString url); void open(in DOMString method, in DOMString url, in boolean async); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password); void setRequestHeader(in DOMString header, in DOMString value); void send(); void send(in DOMString data); void send(in Document data); void abort();
  • 12. Standard definition // response DOMString getAllResponseHeaders(); DOMString getResponseHeader(in DOMString header); readonly attribute DOMString responseText; readonly attribute Document responseXML; readonly attribute unsigned short status; readonly attribute DOMString statusText; };
  • 13. Request states UNSENT = 0 The request is not initialized OPENED = 1 The request has been set up HEADERS_RECEIVED = 2 The request has been sent LOADING = 3 The request is in process DONE = 4 The request is complete
  • 14. State transition diagram .setRequestHeader() new OPENED OPENED UNSENT .open() not sent sent .send() .send() Connection closed All headers received DONE DONE LOADING error not error HEADERS (partial) body _RECEIVED Connection closed received
  • 15. XMLHttpRequest properties onreadystatechange stores the function that will process the response from a server xmlHttp.onreadystatechange = function() { ... } readyState holds the status of the server’s response. Each time readyState changes, the onreadystatechange function will be executed. responseText the data sent back from the server can be retrieved with the responseText property
  • 16. Methods open(method, url, async, user, password) method = “GET”, “POST” url = complete URL to request async = true/false (optional, default=true) user, password (optional) Interrupts any on-going send() setRequestHeader(header, value) Adds a new header to the HTTP Request Content-Type is one common header to send Examples: text/xml, application/xml
  • 17. Methods send(data) Initiates the request data = HTTP request body (optional) May be a Document or DOMString The URL was already given in open() send() terminates immediately if async==true, but transfer continues in the background Generates readystatechange events send() transfers data synchronously if async==false
  • 18. Methods getAllResponseHeaders() Return all response headers as a single string, with headers separated by CR+LF Invalid if UNSENT or OPENED getResponseHeader(header) Returns the value of a single header Invalid if UNSENT or OPENED
  • 19. Receiving the response body responseText of type DOMString If LOADING (partial body) or DONE Allow access to a “raw string” of the response body responseXML of type Document Only if DONE For text/xml (or application/xml or *+xml) content types, otherwise null Allows access to the DOM of the XML document
  • 20. Example Create a standard HTML form with two text fields: username and time. The username field will be filled in by the user and the time field will be filled in using AJAX. No submit button is needed.
  • 21. Example <html> <body> <form name="myForm"> Name: <input type="text" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>
  • 22. Creating an XMLHttpRequest object <script type="text/javascript"> function ajaxFunction() { var xmlHttp; xmlHttp=new XMLHttpRequest(); ... } </script>
  • 23. Supporting all browsers <script type="text/javascript"> function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { // Internet Explorer 6.0+ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { // Internet Explorer 5.5+ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } } </script>
  • 25. Processing the response xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { // Get the data from the server's response document.myForm.time.value=xmlHttp.responseText; } }
  • 26. Attaching to an event <form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" / > Time: <input type="text" name="time" /> </form>
  • 27. Complete example <html> <body> <script type="text/javascript"> function ajaxFunction() { var xmlHttp=new XMLHttpRequest(); xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); } </script> <form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>
  • 30. Exercise 1 Create an auto-complete feature for entering the name in a FORM For every typed letter, an associated text must be updated, reflecting the list of all possible names with those initial(s) Once submitted, the name adds up to the list Clicking on the suggestion auto-fills the box Name Jo Suggestions: Joe, Joseph, John SUBMIT
  • 31. Exercise 2 Create a FORM for entering the name of a city, based on two drop-down menus (<select> tags). The first <select> contains the list of all provinces (AO, BO, CN, MI, TO, ...) The second <select> contains the list of all cities in the province Every time the user changes the province, then the list of cities MUST be updated The form may be submitted only if information is complete