SlideShare a Scribd company logo
Asynchronous JavaScript & XML (AJAX) Compiled by  Adnan Sohail Software Engineer  i2c inc.
Web 2.0 Definition The term has been coined and defined by O'Reilly for designating the use of technologies that improve the design of Web site, allows for collaborative work, create a social networking.  New tools allow to concentrate on the content that is managed automatically.  Web application and Web service become a bigger part of the industry. Examples Gmail, LinkedIn, Facebook and Orkut etc.
Problems of Conventional Web Application Interruption of user operation Users cannot perform any operation while waiting for a response Loss of operational context during refresh Loss of information on the screen Loss of scrolled position No instant feedback's to user activities A user has to wait for the next page Constrained by HTML Lack of useful widgets
Why Ajax? Spontaneous and natural user interaction No clicking required; mouse movement is a sufficient event trigger "Partial screen update" replaces the "click, wait, and refresh" user interaction model Only user interface elements that contain new information are updated (fast response) The rest of the user interface remains displayed without interruption (no loss of operational context) Data-driven (as opposed to page-driven) UI is handled in the client while the server provides data Asynchronous communication replaces "synchronous request/response model.” A user can continue to use the application while the client program requests information from the server in the background Separation of displaying from data fetching
Defining Ajax Standards-based presentation using HTML and CSS;  Dynamic display and interaction using the Document Object Model;  Data interchange and manipulation using JSON, XML and XSLT;  Asynchronous data retrieval using XMLHttpRequest;  JavaScript binding everything together.
Classic Web Application Model Most user actions in the interface trigger an HTTP request back to a web server.  The server does some processing — retrieving data, crunching numbers, talking to various legacy systems — and then returns an HTML page to the client.  Synchronous request response mechanism
 
 
Ajax Engine An Ajax application places an intermediary between the user and the server called  Ajax Engine  (also known as JavaScript part of a web page). It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame.  This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf.  The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.
How Ajax works? Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax Engine instead.  Any response to a user action that doesn’t require a trip back to the server — such as simple data validation, editing data in memory, and even some navigation — the engine handles on its own.  If the engine needs something from the server in order to respond — if it’s submitting data for processing, loading additional interface code, or retrieving new data — the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application.
Underlying technologies JavaScript Loosely typed scripting language JavaScript function is called when an event in a page occurs Glue for the whole AJAX operation DOM API for accessing and manipulating structured documents Represents the structure of XML and HTML documents CSS Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript XMLHttpRequest JavaScript object that performs asynchronous interaction with the server
Steps of Ajax Operation
Steps of Ajax Operation A client event occurs An XMLHttpRequest object is created The XMLHttpRequest object is configured The XMLHttpRequest object makes an async. Request The ValidateServlet returns an XML document containing the result The XMLHttpRequest object calls the callback() function and processes the result The HTML DOM is updated
Starting from the browser… Your browser  must  allow JavaScript, or Ajax won’t work Otherwise, there’s nothing special required of the browser Your browser has some some way of providing data to the server—usually from an HTML form JavaScript has to handle events from the form, create an  XMLHttpRequest  object, and send it (via HTTP) to the server Nothing special is required of the server—every server can handle HTTP requests Despite the name, the  XMLHttpRequest  object does not require XML
The  XMLHttpRequest   object JavaScript has to create an  XMLHttpRequest  object For historical reasons, there are three ways of doing this For most browsers, just do var request = new XMLHttpRequest(); For some versions of Internet Explorer, do var request = new ActiveXObject("Microsoft.XMLHTTP"); For other versions of Internet Explorer, do var request = new ActiveXObject("Msxml2.XMLHTTP"); The next slide shows a JavaScript function for choosing the right way to create an  XMLHttpRequest  object
Getting the  XMLHttpRequest   object function getXMLHttpRequest {   var request = false;   try { request = new XMLHttpRequest(); }   catch(err1) {   try { var request = new ActiveXObject("Microsoft.XMLHTTP"); }   catch(err2) {   try { var request = new ActiveXObject("Msxml2.XMLHTTP"); }   catch(err3) {   request = false;   }   } }   return request; }
Preparing the  XMLHttpRequest   object Once you have an  XMLHttpRequest  object, you have to prepare it with the  open  method request .open( method ,  URL ,  asynchronous ) The  method  is usually  'GET'  or  'POST ' The  URL  is where you are sending the data If using a  'GET' , data is appended to the URL If using a  'POST' , data is added in a later step If  asynchronous  is  true , the browser does not wait for a response (this is what you usually want) request .open( method ,  URL ) As above, with  asynchronous  defaulting to  true
Sending the  XMLHttpRequest   object Once the  XMLHttpRequest  object has been prepared, you have to send it request .send(null); This is the version you use with a  GET  request request .send( content ); This is the version you use with a  POST  request The content has the same syntax as the suffix to a  GET  request POST  requests are used less frequently than  GET  requests Example: request.send('var1=' +  value1  + '&var2=' +  value2 );
Some more methods of  XMLHttpRequest   object abort() Terminates current request getAllResponseHeaders() Returns headers (labels + values) as a string getResponseHeader(“header”) Returns value of a given header setRequestHeader(“label”,”value”) Sets Request Headers before sending
XMLHttpRequest Properties onreadystatechange Set with an JavaScript event handler that fires at each state change readyState  – current status of request 0 = uninitialized 1 = loading 2 = loaded 3 = interactive (some data has been returned) 4 = complete status HTTP Status returned from server: 200 = OK responseText String version of data returned from the server responseXML XML document of data returned from the server statusText Status text returned from server
On the server side The server gets a completely standard HTTP request In a servlet, this would go to a  doGet  or  doPost  method The response is a completely standard HTTP response Instead of returning a complete HTML page as a response, the server returns an arbitrary text string (possibly XML, possibly something else)
Getting the response Ajax uses asynchronous calls—you don’t wait for the response Instead, you have to handle an event request.onreadystatechange = someFunction; This is a function assignment,  not  a function call When the function is called, it will be called with no parameters function someFunction() {   if(request.readyState == 4){   var response = request.responseText;   //  Do something with the response   } } To be safe, set up the handler  before  you call the  send  function
Using response data When you specify the callback function,   request.onreadystatechange = someFunction;   you can’t specify arguments Two solutions: Your function can use the request object as a global variable This is a very bad idea if you have multiple simultaneous requests You can assign an anonymous function:   request.onreadystatechange = function() { someFunction(request); } Here the anonymous function calls your  someFunction  with the request object as an argument.
Displaying the response http_request.onreadystatechange =   function() { alertContents(http_request); }; http_request.open('GET', url, true); http_request.send(null); function alertContents(http_request) {   if (http_request.readyState == 4) { /* 4 means got the response */   if (http_request.status == 200) {   alert(http_request.responseText);   } else {   alert('There was a problem with the request.');   }   } }
The  readyState  property The  readyState  property defines the current state of the  XMLHttpRequest  object. Here are the possible values for the  readyState  property: readyState=0  after you have created the  XMLHttpRequest  object, but before you have called the  open()  method. readyState=1  after you have called the  open()  method, but before you have called  send() . readyState=2  after you have called  send() . r eadyState=3  after the browser has established a communication with the server, but before the server has completed the response. readyState=4  after the request has been completed, and the response data have been completely received from the server. Not all browsers use all states Usually you are only interested in state  4
Doing it with XML Here’s an XML file named  test.xml : <?xml version=&quot;1.0&quot; ?> <root> I'm a test. </root> Then in  alertContents()  from the previous slide, we need to replace the line   alert(http_request. responseText ); with:   var xmldoc = http_request. responseXML ;   var root_node =   xmldoc.getElementsByTagName('root').item(0);   alert(root_node.firstChild.data);  From:  http://developer.mozilla.org/en/docs/AJAX:Getting_Started
XML notes The XML response object supports very complete XML DOM processing The response header must include: Content-Type: application/xml or IE will throw an “Object expected” JavaScript error Cache-Control: no-cache or the response will be cached and the request will never be resubmitted For some browsers you may need to do request . overrideMimeType('text/xml'); In Firefox, this will give an error if the response isn’t valid XML
innerHTML innerHTML  is a non-W3C DOM property that gets or sets the text between start and end tags of an HTML element When the  innerHTML  property is set, the given string completely replaces the existing content of the object If the string contains HTML tags, the string is parsed and formatted as it is placed into the document  Syntax: var  markup  = element.innerHTML; element.innerHTML =  markup ; Example: document.getElementById( someId ).innerHTML =  response ;
Use Cases of Ajax Real-time form data validation Autocompletion Load on demand Sophisticated UI controls and effects Refreshing data and server push Partial submit
Pros and Cons Pros Most viable RIA technology so far Tremendous industry momentum Several toolkits and frameworks are emerging No need to download code & no plug-in required Cons Still browser incompatibility JavaScript is hard to maintain and debug May break expected behavior of browser’s Back Button
References http://www.xul.fr/web-2.0.html  http://www.adaptivepath.com/ideas/essays/archives/000385.php http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp http://www.xml.com/pub/a/2005/02/09/xml-http-request.html http://developer.mozilla.org/en/docs/AJAX:Getting_Started https://developer.mozilla.org/en/XMLHttpRequest SAMS Teach Yourself Ajax in 10 Minutes, Phil Ballard, p.  85 JavaScript & AJAX, 6 th  Edition, Tom Negrino and Dori Smith, ch. 15 Ajax Basic by Sang Shin Sang Shin (Java Technology Architect), Sun Microsystems, Inc. Sun Microsystems, Inc. [sang.shin@sun.com], www.javapassion.com

More Related Content

What's hot (20)

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
MAGNA COLLEGE OF ENGINEERING
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
NexThoughts Technologies
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
priya Nithya
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
Naveen Sihag
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Nir Elbaz
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
priya Nithya
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Nir Elbaz
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 

Viewers also liked (13)

AJAX
AJAXAJAX
AJAX
Mukesh Tekwani
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
Hema Prasanth
 
TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI
yogita kachve
 
XML DOM
XML DOMXML DOM
XML DOM
Hoang Nguyen
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
Mukesh Tekwani
 
TYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
TYBCom Computer Systems and Applications - Sem 6 - University of MumbaiTYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
TYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
Mukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
Mukesh Tekwani
 
Tugas[1] 0317-[tryanita]-[1411511676]
Tugas[1] 0317-[tryanita]-[1411511676]Tugas[1] 0317-[tryanita]-[1411511676]
Tugas[1] 0317-[tryanita]-[1411511676]
trya nita
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
Tugas[2] 0317-[Wildan Latief]-[1512500818]
Tugas[2] 0317-[Wildan Latief]-[1512500818]Tugas[2] 0317-[Wildan Latief]-[1512500818]
Tugas[2] 0317-[Wildan Latief]-[1512500818]
wieldhant latief
 
Tugas[4] 0317-[tryanita]-[1411511676]
Tugas[4]  0317-[tryanita]-[1411511676]Tugas[4]  0317-[tryanita]-[1411511676]
Tugas[4] 0317-[tryanita]-[1411511676]
trya nita
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
Salim M
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
simran153
 
TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI
yogita kachve
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
Mukesh Tekwani
 
TYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
TYBCom Computer Systems and Applications - Sem 6 - University of MumbaiTYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
TYBCom Computer Systems and Applications - Sem 6 - University of Mumbai
Mukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
Mukesh Tekwani
 
Tugas[1] 0317-[tryanita]-[1411511676]
Tugas[1] 0317-[tryanita]-[1411511676]Tugas[1] 0317-[tryanita]-[1411511676]
Tugas[1] 0317-[tryanita]-[1411511676]
trya nita
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
Tugas[2] 0317-[Wildan Latief]-[1512500818]
Tugas[2] 0317-[Wildan Latief]-[1512500818]Tugas[2] 0317-[Wildan Latief]-[1512500818]
Tugas[2] 0317-[Wildan Latief]-[1512500818]
wieldhant latief
 
Tugas[4] 0317-[tryanita]-[1411511676]
Tugas[4]  0317-[tryanita]-[1411511676]Tugas[4]  0317-[tryanita]-[1411511676]
Tugas[4] 0317-[tryanita]-[1411511676]
trya nita
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
Salim M
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
simran153
 
Ad

Similar to Asynchronous JavaScript & XML (AJAX) (20)

Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
WebVineet
 
Ajax
AjaxAjax
Ajax
Svirid
 
Ajax
AjaxAjax
Ajax
Manav Prasad
 
Web Programming using Asynchronous JavaX
Web Programming using Asynchronous JavaXWeb Programming using Asynchronous JavaX
Web Programming using Asynchronous JavaX
SivanN6
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
sawsan slii
 
Ajax
AjaxAjax
Ajax
husnara mohammad
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
Ganesh Chavan
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
ssuser0a07a1
 
Ajax
AjaxAjax
Ajax
baabtra.com - No. 1 supplier of quality freshers
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
Unit Nexus Pvt. Ltd.
 
AJAX.ppt
AJAX.pptAJAX.ppt
AJAX.ppt
karan419841
 
Ajax Overview by Bally Chohan
Ajax Overview by Bally ChohanAjax Overview by Bally Chohan
Ajax Overview by Bally Chohan
WebVineet
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
itzkuu01
 
Ajax
AjaxAjax
Ajax
Abhishek Kesharwani
 
AJAX
AJAXAJAX
AJAX
ankurgupta
 
Ajax
AjaxAjax
Ajax
Dumindu Pahalawatta
 
Ajax
AjaxAjax
Ajax
NIRMAL FELIX
 
Ajax
AjaxAjax
Ajax
ch samaram
 
Ajax
AjaxAjax
Ajax
TSUBHASHRI
 
Ad

Recently uploaded (20)

Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 

Asynchronous JavaScript & XML (AJAX)

  • 1. Asynchronous JavaScript & XML (AJAX) Compiled by Adnan Sohail Software Engineer i2c inc.
  • 2. Web 2.0 Definition The term has been coined and defined by O'Reilly for designating the use of technologies that improve the design of Web site, allows for collaborative work, create a social networking. New tools allow to concentrate on the content that is managed automatically. Web application and Web service become a bigger part of the industry. Examples Gmail, LinkedIn, Facebook and Orkut etc.
  • 3. Problems of Conventional Web Application Interruption of user operation Users cannot perform any operation while waiting for a response Loss of operational context during refresh Loss of information on the screen Loss of scrolled position No instant feedback's to user activities A user has to wait for the next page Constrained by HTML Lack of useful widgets
  • 4. Why Ajax? Spontaneous and natural user interaction No clicking required; mouse movement is a sufficient event trigger &quot;Partial screen update&quot; replaces the &quot;click, wait, and refresh&quot; user interaction model Only user interface elements that contain new information are updated (fast response) The rest of the user interface remains displayed without interruption (no loss of operational context) Data-driven (as opposed to page-driven) UI is handled in the client while the server provides data Asynchronous communication replaces &quot;synchronous request/response model.” A user can continue to use the application while the client program requests information from the server in the background Separation of displaying from data fetching
  • 5. Defining Ajax Standards-based presentation using HTML and CSS; Dynamic display and interaction using the Document Object Model; Data interchange and manipulation using JSON, XML and XSLT; Asynchronous data retrieval using XMLHttpRequest; JavaScript binding everything together.
  • 6. Classic Web Application Model Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing — retrieving data, crunching numbers, talking to various legacy systems — and then returns an HTML page to the client. Synchronous request response mechanism
  • 7.  
  • 8.  
  • 9. Ajax Engine An Ajax application places an intermediary between the user and the server called Ajax Engine (also known as JavaScript part of a web page). It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.
  • 10. How Ajax works? Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax Engine instead. Any response to a user action that doesn’t require a trip back to the server — such as simple data validation, editing data in memory, and even some navigation — the engine handles on its own. If the engine needs something from the server in order to respond — if it’s submitting data for processing, loading additional interface code, or retrieving new data — the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application.
  • 11. Underlying technologies JavaScript Loosely typed scripting language JavaScript function is called when an event in a page occurs Glue for the whole AJAX operation DOM API for accessing and manipulating structured documents Represents the structure of XML and HTML documents CSS Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript XMLHttpRequest JavaScript object that performs asynchronous interaction with the server
  • 12. Steps of Ajax Operation
  • 13. Steps of Ajax Operation A client event occurs An XMLHttpRequest object is created The XMLHttpRequest object is configured The XMLHttpRequest object makes an async. Request The ValidateServlet returns an XML document containing the result The XMLHttpRequest object calls the callback() function and processes the result The HTML DOM is updated
  • 14. Starting from the browser… Your browser must allow JavaScript, or Ajax won’t work Otherwise, there’s nothing special required of the browser Your browser has some some way of providing data to the server—usually from an HTML form JavaScript has to handle events from the form, create an XMLHttpRequest object, and send it (via HTTP) to the server Nothing special is required of the server—every server can handle HTTP requests Despite the name, the XMLHttpRequest object does not require XML
  • 15. The XMLHttpRequest object JavaScript has to create an XMLHttpRequest object For historical reasons, there are three ways of doing this For most browsers, just do var request = new XMLHttpRequest(); For some versions of Internet Explorer, do var request = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); For other versions of Internet Explorer, do var request = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;); The next slide shows a JavaScript function for choosing the right way to create an XMLHttpRequest object
  • 16. Getting the XMLHttpRequest object function getXMLHttpRequest { var request = false; try { request = new XMLHttpRequest(); } catch(err1) { try { var request = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } catch(err2) { try { var request = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;); } catch(err3) { request = false; } } } return request; }
  • 17. Preparing the XMLHttpRequest object Once you have an XMLHttpRequest object, you have to prepare it with the open method request .open( method , URL , asynchronous ) The method is usually 'GET' or 'POST ' The URL is where you are sending the data If using a 'GET' , data is appended to the URL If using a 'POST' , data is added in a later step If asynchronous is true , the browser does not wait for a response (this is what you usually want) request .open( method , URL ) As above, with asynchronous defaulting to true
  • 18. Sending the XMLHttpRequest object Once the XMLHttpRequest object has been prepared, you have to send it request .send(null); This is the version you use with a GET request request .send( content ); This is the version you use with a POST request The content has the same syntax as the suffix to a GET request POST requests are used less frequently than GET requests Example: request.send('var1=' + value1 + '&var2=' + value2 );
  • 19. Some more methods of XMLHttpRequest object abort() Terminates current request getAllResponseHeaders() Returns headers (labels + values) as a string getResponseHeader(“header”) Returns value of a given header setRequestHeader(“label”,”value”) Sets Request Headers before sending
  • 20. XMLHttpRequest Properties onreadystatechange Set with an JavaScript event handler that fires at each state change readyState – current status of request 0 = uninitialized 1 = loading 2 = loaded 3 = interactive (some data has been returned) 4 = complete status HTTP Status returned from server: 200 = OK responseText String version of data returned from the server responseXML XML document of data returned from the server statusText Status text returned from server
  • 21. On the server side The server gets a completely standard HTTP request In a servlet, this would go to a doGet or doPost method The response is a completely standard HTTP response Instead of returning a complete HTML page as a response, the server returns an arbitrary text string (possibly XML, possibly something else)
  • 22. Getting the response Ajax uses asynchronous calls—you don’t wait for the response Instead, you have to handle an event request.onreadystatechange = someFunction; This is a function assignment, not a function call When the function is called, it will be called with no parameters function someFunction() { if(request.readyState == 4){ var response = request.responseText; // Do something with the response } } To be safe, set up the handler before you call the send function
  • 23. Using response data When you specify the callback function, request.onreadystatechange = someFunction; you can’t specify arguments Two solutions: Your function can use the request object as a global variable This is a very bad idea if you have multiple simultaneous requests You can assign an anonymous function: request.onreadystatechange = function() { someFunction(request); } Here the anonymous function calls your someFunction with the request object as an argument.
  • 24. Displaying the response http_request.onreadystatechange = function() { alertContents(http_request); }; http_request.open('GET', url, true); http_request.send(null); function alertContents(http_request) { if (http_request.readyState == 4) { /* 4 means got the response */ if (http_request.status == 200) { alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } }
  • 25. The readyState property The readyState property defines the current state of the XMLHttpRequest object. Here are the possible values for the readyState property: readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method. readyState=1 after you have called the open() method, but before you have called send() . readyState=2 after you have called send() . r eadyState=3 after the browser has established a communication with the server, but before the server has completed the response. readyState=4 after the request has been completed, and the response data have been completely received from the server. Not all browsers use all states Usually you are only interested in state 4
  • 26. Doing it with XML Here’s an XML file named test.xml : <?xml version=&quot;1.0&quot; ?> <root> I'm a test. </root> Then in alertContents() from the previous slide, we need to replace the line alert(http_request. responseText ); with: var xmldoc = http_request. responseXML ; var root_node = xmldoc.getElementsByTagName('root').item(0); alert(root_node.firstChild.data); From: http://developer.mozilla.org/en/docs/AJAX:Getting_Started
  • 27. XML notes The XML response object supports very complete XML DOM processing The response header must include: Content-Type: application/xml or IE will throw an “Object expected” JavaScript error Cache-Control: no-cache or the response will be cached and the request will never be resubmitted For some browsers you may need to do request . overrideMimeType('text/xml'); In Firefox, this will give an error if the response isn’t valid XML
  • 28. innerHTML innerHTML is a non-W3C DOM property that gets or sets the text between start and end tags of an HTML element When the innerHTML property is set, the given string completely replaces the existing content of the object If the string contains HTML tags, the string is parsed and formatted as it is placed into the document Syntax: var markup = element.innerHTML; element.innerHTML = markup ; Example: document.getElementById( someId ).innerHTML = response ;
  • 29. Use Cases of Ajax Real-time form data validation Autocompletion Load on demand Sophisticated UI controls and effects Refreshing data and server push Partial submit
  • 30. Pros and Cons Pros Most viable RIA technology so far Tremendous industry momentum Several toolkits and frameworks are emerging No need to download code & no plug-in required Cons Still browser incompatibility JavaScript is hard to maintain and debug May break expected behavior of browser’s Back Button
  • 31. References http://www.xul.fr/web-2.0.html http://www.adaptivepath.com/ideas/essays/archives/000385.php http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp http://www.xml.com/pub/a/2005/02/09/xml-http-request.html http://developer.mozilla.org/en/docs/AJAX:Getting_Started https://developer.mozilla.org/en/XMLHttpRequest SAMS Teach Yourself Ajax in 10 Minutes, Phil Ballard, p. 85 JavaScript & AJAX, 6 th Edition, Tom Negrino and Dori Smith, ch. 15 Ajax Basic by Sang Shin Sang Shin (Java Technology Architect), Sun Microsystems, Inc. Sun Microsystems, Inc. [[email protected]], www.javapassion.com