-By V.Gouthaman
INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.
ASYNCHRONOUS REQUEST AND RESPONSE
The Anatomy of an Ajax Interaction Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
 
Now let's look at each step of the Ajax interaction in more detail. A client event occurs. JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component.
<input type=&quot;text&quot; size=&quot;20&quot;  id=&quot;userid&quot; name=&quot;id&quot; onkeyup=&quot;validate();&quot;> This form element will call the validate() function each time the user presses a key in the form field.
2. A XMLHttpRequest object is created and configured. An XMLHttpRequest object is created and configured.  var req; function validate() { var idField = document.getElementById(&quot;userid&quot;); var url = &quot;validate?id=&quot; + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != &quot;undefined&quot;) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } req.open(&quot;GET&quot;, url, true); req.onreadystatechange = callback; req.send(null); }
The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
3. The XMLHttpRequest object makes a call. When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter.  Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:
req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); req.send(&quot;id=&quot; + encodeURIComponent(idTextField.value)); When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
4. The request is processed by the ValidateServlet. A servlet mapped to the URI &quot;validate&quot; checks whether the user ID is in the user database.A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken.  public class ValidateServlet extends  HttpServlet { private ServletContext context;   private HashMap users = new HashMap(); public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); users.put(&quot;greg&quot;,&quot;account data&quot;); users.put(&quot;duke&quot;,&quot;account data&quot;); }
public void doGet(HttpServletRequest request, HttpServletResponse  response) throws IOException, ServletException { String targetId = request.getParameter(&quot;id&quot;); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>valid</message>&quot;);  } else  { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;);  } } } In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
5. The ValidateServlet returns an XML document containing the results. The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the  response.response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;)
6. The XMLHttpRequest object calls the callback() function and processes the result. The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction. function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } }
Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded. Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
<message> valid </message> This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user: function parseMessage() { var message = req.responseXML.getElementsByTagName(&quot;message&quot;)[0]; setMessage(message.childNodes[0].nodeValue); } The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
7. The HTML DOM is updated. JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById(&quot;userIdMessage&quot;), where &quot;userIdMessage&quot; is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements.  One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
<script type=&quot;text/javascript&quot;> ... function setMessage(message) { var mdiv = document.getElementById(&quot;userIdMessage&quot;); if (message == &quot;invalid&quot;) { mdiv.innerHTML = &quot;<div style=\&quot;color:red\&quot;>Invalid User Id</ div>&quot;; } else { mdiv.innerHTML = &quot;<div style=\&quot;color:green\&quot;>Valid User Id</ div>&quot;; } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body>
The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well. Ajax applications such as Google Maps use this technique of adding image elements using Ajax calls to dynamically build maps. The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hardcoding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit. Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the following example.
<script type=&quot;text/javascript&quot;> ... function setMessage(message) { var userMessageElement = document.getElementById(&quot;userIdMessage&quot;); var messageText; if (message == &quot;invalid&quot;) { userMessageElement.style.color = &quot;red&quot;; messageText = &quot;Invalid User Id&quot;; } else { userMessageElement.style.color = &quot;green&quot;; messageText = &quot;Valid User Id&quot;; }  var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple replace it otherwise
// append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody,  userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body> The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applications.
What is the main strength of AJAX? Or why and when should we use AJAX in web application? The most common answer is – “AJAX does not refresh or reload the whole page”. But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”
In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so. Here is a simple example – function check() { var a=0; a = getStatus(“getstatus.php?id=5”); if(a==1) { alert(“active”); } else { alert(“not active”); } }
Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0. But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request. The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null. So, how should we work with asynchronous request? Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).
 

More Related Content

PDF
Web II - 02 - How ASP.NET Works
PDF
ajax_pdf
PDF
PPT
Xml http request
PDF
RicoAjaxEngine
PDF
Servlets intro
PDF
Url programming
PPT
Simple Data Binding
Web II - 02 - How ASP.NET Works
ajax_pdf
Xml http request
RicoAjaxEngine
Servlets intro
Url programming
Simple Data Binding

What's hot (17)

PDF
&lt;img src="../i/r_14.png" />
PPT
Pascarello_Investigating JavaScript and Ajax Security
PDF
ASPNET_MVC_Tutorial_06_CS
PPTX
Academy PRO: ASP .NET Core MVC
ODP
Creating a Java EE 7 Websocket Chat Application
PDF
Data Binding
PPTX
State management
PDF
J2EE jsp_03
DOCX
My Portfolio
PPT
PDF
MongoDB Stitch Tutorial
PPTX
Programming web application
PPTX
Windows 8 metro applications
PPT
Understanding AJAX
PPT
Asp db
PDF
Mvc acchitecture
PDF
Remote code-with-expression-language-injection
&lt;img src="../i/r_14.png" />
Pascarello_Investigating JavaScript and Ajax Security
ASPNET_MVC_Tutorial_06_CS
Academy PRO: ASP .NET Core MVC
Creating a Java EE 7 Websocket Chat Application
Data Binding
State management
J2EE jsp_03
My Portfolio
MongoDB Stitch Tutorial
Programming web application
Windows 8 metro applications
Understanding AJAX
Asp db
Mvc acchitecture
Remote code-with-expression-language-injection
Ad

Viewers also liked (19)

PDF
Linkedin pro docs/ how to VII
PDF
Software librea ibarrekolanda
PDF
Linkedin pro docs/ how to VI
PDF
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
PDF
500mW, 1W RF Data Transmitter, 433MHz RF Module
DOC
Combinational circuits II outputs
XLS
Scholastic averages sheet-2
PPT
PDF
Judo sponsorship 2012
PDF
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
PDF
Feasibility Studies: 2-EH Manufacturing
PPSX
Comprendre, developper et analyser son influence sur les reseaux sociaux
PDF
Economics of Citric Acid Production Processes
PDF
Feasibility Studies: Hexenes Manufacturing
PDF
Economic Analysis: Styrene Production Processes
PPTX
Phonegap
PPTX
Média sociaux: evolution ou révolution (Belfius 17/05/2014)
PDF
Health Rights & the PRIDE Project in Pakistan
PPTX
Exp Social Marketing Foundation, Ghana
Linkedin pro docs/ how to VII
Software librea ibarrekolanda
Linkedin pro docs/ how to VI
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
500mW, 1W RF Data Transmitter, 433MHz RF Module
Combinational circuits II outputs
Scholastic averages sheet-2
Judo sponsorship 2012
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
Feasibility Studies: 2-EH Manufacturing
Comprendre, developper et analyser son influence sur les reseaux sociaux
Economics of Citric Acid Production Processes
Feasibility Studies: Hexenes Manufacturing
Economic Analysis: Styrene Production Processes
Phonegap
Média sociaux: evolution ou révolution (Belfius 17/05/2014)
Health Rights & the PRIDE Project in Pakistan
Exp Social Marketing Foundation, Ghana
Ad

Similar to AJAX (20)

PPT
Asynchronous JavaScript & XML (AJAX)
PPT
Ajax tutorial by bally chohan
PPT
PDF
ajax_pdf
PPT
Ajax
PPS
RIA and Ajax
PPTX
PPTX
Ajax Technology
PDF
How to make Ajax work for you
PDF
Ajax chap 5
PDF
Introduction to Ajax programming
PPT
PDF
AJAX Transport Layer
PPT
Web Programming using Asynchronous JavaX
PPTX
Data and information about anatical subject
PPTX
Unit-5.pptx
PPTX
ajax - the basics
PPTX
Ajax enabled rich internet applications with xml and json
Asynchronous JavaScript & XML (AJAX)
Ajax tutorial by bally chohan
ajax_pdf
Ajax
RIA and Ajax
Ajax Technology
How to make Ajax work for you
Ajax chap 5
Introduction to Ajax programming
AJAX Transport Layer
Web Programming using Asynchronous JavaX
Data and information about anatical subject
Unit-5.pptx
ajax - the basics
Ajax enabled rich internet applications with xml and json

More from Gouthaman V (20)

PDF
Professional Ethics Assignment II
DOC
Dip Unit Test-I
DOC
Eligibility criteria and instructions for Infosys Placement
PDF
Answers for 2 Marks Unit Test I (RMW)
PDF
Anwers for 2 marks - RMW
PDF
Rmw unit test question papers
PDF
Circular and semicircular cavity resonator
DOC
VLSI Anna University Practical Examination
DOC
HCL IPT
DOC
VLSI Sequential Circuits II
PDF
VI Semester Examination Time Table
DOC
DOC
Antenna and Wave Propagation Assignment I
DOC
Antenna and Wave Propagation Assignment I
DOC
Computer Networks Unit Test II Questions
DOC
Sequential Circuits I VLSI 9th experiment
DOC
Antenna Unit Test II Questions
DOC
Antenna Unit Test II questions
DOC
POM Unit Test II - ECE B
DOC
All VLSI programs
Professional Ethics Assignment II
Dip Unit Test-I
Eligibility criteria and instructions for Infosys Placement
Answers for 2 Marks Unit Test I (RMW)
Anwers for 2 marks - RMW
Rmw unit test question papers
Circular and semicircular cavity resonator
VLSI Anna University Practical Examination
HCL IPT
VLSI Sequential Circuits II
VI Semester Examination Time Table
Antenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment I
Computer Networks Unit Test II Questions
Sequential Circuits I VLSI 9th experiment
Antenna Unit Test II Questions
Antenna Unit Test II questions
POM Unit Test II - ECE B
All VLSI programs

Recently uploaded (20)

PPTX
4. Diagnosis and treatment planning in RPD.pptx
PDF
0520_Scheme_of_Work_(for_examination_from_2021).pdf
PDF
FYJC - Chemistry textbook - standard 11.
DOCX
EDUCATIONAL ASSESSMENT ASSIGNMENT SEMESTER MAY 2025.docx
PDF
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
PDF
African Communication Research: A review
PPTX
Integrated Management of Neonatal and Childhood Illnesses (IMNCI) – Unit IV |...
PPTX
Why I Am A Baptist, History of the Baptist, The Baptist Distinctives, 1st Bap...
PPTX
BSCE 2 NIGHT (CHAPTER 2) just cases.pptx
PPTX
Macbeth play - analysis .pptx english lit
PPTX
Thinking Routines and Learning Engagements.pptx
PDF
Health aspects of bilberry: A review on its general benefits
PDF
Compact First Student's Book Cambridge Official
PPTX
Neurological complocations of systemic disease
PDF
Chevening Scholarship Application and Interview Preparation Guide
PDF
Lecture on Viruses: Structure, Classification, Replication, Effects on Cells,...
PPT
Acidosis in Dairy Herds: Causes, Signs, Management, Prevention and Treatment
PDF
The TKT Course. Modules 1, 2, 3.for self study
PPTX
ACFE CERTIFICATION TRAINING ON LAW.pptx
PDF
Solved Past paper of Pediatric Health Nursing PHN BS Nursing 5th Semester
4. Diagnosis and treatment planning in RPD.pptx
0520_Scheme_of_Work_(for_examination_from_2021).pdf
FYJC - Chemistry textbook - standard 11.
EDUCATIONAL ASSESSMENT ASSIGNMENT SEMESTER MAY 2025.docx
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
African Communication Research: A review
Integrated Management of Neonatal and Childhood Illnesses (IMNCI) – Unit IV |...
Why I Am A Baptist, History of the Baptist, The Baptist Distinctives, 1st Bap...
BSCE 2 NIGHT (CHAPTER 2) just cases.pptx
Macbeth play - analysis .pptx english lit
Thinking Routines and Learning Engagements.pptx
Health aspects of bilberry: A review on its general benefits
Compact First Student's Book Cambridge Official
Neurological complocations of systemic disease
Chevening Scholarship Application and Interview Preparation Guide
Lecture on Viruses: Structure, Classification, Replication, Effects on Cells,...
Acidosis in Dairy Herds: Causes, Signs, Management, Prevention and Treatment
The TKT Course. Modules 1, 2, 3.for self study
ACFE CERTIFICATION TRAINING ON LAW.pptx
Solved Past paper of Pediatric Health Nursing PHN BS Nursing 5th Semester

AJAX

  • 2. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
  • 3. Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.
  • 5. The Anatomy of an Ajax Interaction Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
  • 6.  
  • 7. Now let's look at each step of the Ajax interaction in more detail. A client event occurs. JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component.
  • 8. <input type=&quot;text&quot; size=&quot;20&quot; id=&quot;userid&quot; name=&quot;id&quot; onkeyup=&quot;validate();&quot;> This form element will call the validate() function each time the user presses a key in the form field.
  • 9. 2. A XMLHttpRequest object is created and configured. An XMLHttpRequest object is created and configured. var req; function validate() { var idField = document.getElementById(&quot;userid&quot;); var url = &quot;validate?id=&quot; + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != &quot;undefined&quot;) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } req.open(&quot;GET&quot;, url, true); req.onreadystatechange = callback; req.send(null); }
  • 10. The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
  • 11. 3. The XMLHttpRequest object makes a call. When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter. Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:
  • 12. req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); req.send(&quot;id=&quot; + encodeURIComponent(idTextField.value)); When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
  • 13. 4. The request is processed by the ValidateServlet. A servlet mapped to the URI &quot;validate&quot; checks whether the user ID is in the user database.A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken. public class ValidateServlet extends HttpServlet { private ServletContext context; private HashMap users = new HashMap(); public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); users.put(&quot;greg&quot;,&quot;account data&quot;); users.put(&quot;duke&quot;,&quot;account data&quot;); }
  • 14. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter(&quot;id&quot;); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>valid</message>&quot;); } else { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;); } } } In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
  • 15. 5. The ValidateServlet returns an XML document containing the results. The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the response.response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;)
  • 16. 6. The XMLHttpRequest object calls the callback() function and processes the result. The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction. function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } }
  • 17. Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded. Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
  • 18. <message> valid </message> This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user: function parseMessage() { var message = req.responseXML.getElementsByTagName(&quot;message&quot;)[0]; setMessage(message.childNodes[0].nodeValue); } The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
  • 19. 7. The HTML DOM is updated. JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById(&quot;userIdMessage&quot;), where &quot;userIdMessage&quot; is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements. One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
  • 20. <script type=&quot;text/javascript&quot;> ... function setMessage(message) { var mdiv = document.getElementById(&quot;userIdMessage&quot;); if (message == &quot;invalid&quot;) { mdiv.innerHTML = &quot;<div style=\&quot;color:red\&quot;>Invalid User Id</ div>&quot;; } else { mdiv.innerHTML = &quot;<div style=\&quot;color:green\&quot;>Valid User Id</ div>&quot;; } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body>
  • 21. The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well. Ajax applications such as Google Maps use this technique of adding image elements using Ajax calls to dynamically build maps. The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hardcoding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit. Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the following example.
  • 22. <script type=&quot;text/javascript&quot;> ... function setMessage(message) { var userMessageElement = document.getElementById(&quot;userIdMessage&quot;); var messageText; if (message == &quot;invalid&quot;) { userMessageElement.style.color = &quot;red&quot;; messageText = &quot;Invalid User Id&quot;; } else { userMessageElement.style.color = &quot;green&quot;; messageText = &quot;Valid User Id&quot;; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple replace it otherwise
  • 23. // append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body> The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applications.
  • 24. What is the main strength of AJAX? Or why and when should we use AJAX in web application? The most common answer is – “AJAX does not refresh or reload the whole page”. But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”
  • 25. In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so. Here is a simple example – function check() { var a=0; a = getStatus(“getstatus.php?id=5”); if(a==1) { alert(“active”); } else { alert(“not active”); } }
  • 26. Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0. But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request. The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null. So, how should we work with asynchronous request? Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).
  • 27.