Published on

Introduction to AJAX , Asynchronous Request and Response.

Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. -By V.Gouthaman
  2. 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. 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. 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. <ul><li>Now let's look at each step of the Ajax interaction in more detail. </li></ul><ul><li>A client event occurs. </li></ul><ul><li>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. </li></ul>
  7. 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.
  8. 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); }
  9. 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.
  10. 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:
  11. 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.
  12. 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;); }
  13. 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.
  14. 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;)
  15. 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 } } }
  16. 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.
  17. 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.
  18. 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.
  19. 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>
  20. 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.
  21. 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
  22. 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.
  23. 24. What is the main strength of AJAX? Or why and when should we use AJAX in web application? <ul><li>The most common answer is – “AJAX does not refresh or reload the whole page”. </li></ul><ul><li>But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.” </li></ul>
  24. 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”); } }
  25. 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).