Presentation is loading. Please wait.

Presentation is loading. Please wait.

-By V.Gouthaman. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side.

Similar presentations


Presentation on theme: "-By V.Gouthaman. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side."— Presentation transcript:

1 -By V.Gouthaman

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.

4 ASYNCHRONOUS REQUEST AND RESPONSE

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. 1.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="text" size="20" id="userid" name="id" onkeyup="validate();"> 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("userid"); var url = "validate?id=" + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", 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("Content-Type", "application/x- www-form-urlencoded"); req.send("id=" + 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 "validate" 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("greg","account data"); users.put("duke","account data"); }

14 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" valid "); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid "); } 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("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid ")

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 valid 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("message")[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("userIdMessage"), where "userIdMessage" 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 ... function setMessage(message) { var mdiv = document.getElementById("userIdMessage"); if (message == "invalid") { mdiv.innerHTML = " Invalid User Id "; } else { mdiv.innerHTML = " Valid User Id "; }

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 or, 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 ... function setMessage(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "invalid") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } 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); } 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


Download ppt "-By V.Gouthaman. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side."

Similar presentations


Ads by Google