Ajax

906 views

Published on

Ajax by Atul Kahate Sir at SICSR

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
906
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
56
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Ajax

  1. 1. AJAX Atul Kahate akahate@gmail.com
  2. 2. Traditional HTTP Processing Request- response pairs (Synchronous Web Server in nature) Web Brows er AJAX | Atul Kahate 2
  3. 3. AJAX-based Processing Web Server Asynchronous JavaScript operation <script> Web function Brows abc() { …} er Update AJAX | Atul Kahate 3
  4. 4. What is AJAX? Asynchronous JavaScript and XML Allows for asynchronous communication between a browser (client) and server Does not mandate that the end user must wait for processing a request Can be used as an alternative to HTML forms in certain situations AJAX | Atul Kahate 4
  5. 5. AJAX – Basic FAQ – 1 Do we not use request/response model in AJAX? We do, but the approach is different now. We do not submit a form now, but instead send requests using JavaScript Why not submit the form? Why AJAX? AJAX processing is asynchronous. Client does not wait for server to respond. When server responds, JavaScript does not refresh the whole page. AJAX | Atul Kahate 5
  6. 6. AJAX – Basic FAQ – 2 How does a page get back a response, then? When the server sends a response, JavaScript can update a page with new values, change an image, or transfer control to a new page. The user does not have to wait while this happens. Should we use AJAX for all our requests? No. Traditional form filling is still required in many situations. But for immediate and intermediate responses/feedbacks, we should use AJAX. AJAX | Atul Kahate 6
  7. 7. AJAX – Basic FAQ – 3 Where is the XML in AJAX? Sometimes the JavaScript can use XML to speak with the server back and forth. AJAX | Atul Kahate 7
  8. 8. AJAX: Technical Details
  9. 9. Writing AJAX Ability to fetch data from the server without having to refresh a page Applications without AJAX Normal Web applications communicate with the server by referring to a new URL Example: When a form is submitted, it is processed by a server-side program, which gets invoked AJAX applications Use an object called as XMLHttpRequest object built into the browser, using JavaScript to communicate with the server HTML form is not needed to communicate with the server AJAX | Atul Kahate 9
  10. 10. The XMLHttpRequest Object Alternative for HTML forms Used to communicate with the server side code, from inside a browser Server side code now returns text or XML data, not the complete HTML Web page Programmer has to extract data received from the server via the XMLHttpRequest object, as per the needs AJAX | Atul Kahate 10
  11. 11. AJAX Steps1. Create a request object2. Tell the request object where to send the request3. Tell the object what to do when the request is answered4. Tell the object to make a request AJAX | Atul Kahate 11
  12. 12. XMLHttpRequest Object –Technical Details In some browsers, this object is native (part of the browser); in some others, it needs to be downloaded (as an ActiveX control) Accordingly, coding changes across browser versions as well AJAX | Atul Kahate 12
  13. 13. Ajax Sequence Diagram AJAX | Atul Kahate 13
  14. 14. Step 1: Create theXMLHttpRequest Object
  15. 15. Creating an XMLHttpRequestObject Using JavaScript – 1 Two main browsers are required to be handled: Internet Explorer and Others Non-IE code var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { // Non-IE browser XMLHttpRequestObject = new XMLHttpRequest (); } IE code else if (window.ActiveXObject) { // IE browser XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } AJAX | Atul Kahate 15
  16. 16. Creating an XMLHttpRequestObject Using JavaScript – 2 Now start writing HTML as usual, after checking for the presence of the XMLHttpRequest object if (XMLHttpRequestObject) { document.write ("<h1>Welcome to AJAX</h1>"); } AJAX | Atul Kahate 16
  17. 17. Creating an XMLHttpRequestObject Using JavaScript – 3 Final code (1.html)<html><head><title>AJAX Example</title><script language = "javascript">var XMLHttpRequestObject = false;if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest ();}else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");}if (XMLHttpRequestObject) { document.write ("<h1>Welcome to AJAX</h1>");}</script></head><body></body></html> AJAX | Atul Kahate 17
  18. 18. Creating an XMLHttpRequestObject Using JavaScript – 4 Output AJAX | Atul Kahate 18
  19. 19. <div> and <span> HTMLElements
  20. 20. <div> and <span> - 1 A <div> HTML container can hold all related elements together and can allow us to style all those elements with one CSS rule<div id=“menu”> <a href=“home.html”>home</a> <a href=“books.html”>writing</a> <a href=“links.html”>links</a> <a href=“lib.html”>lib</a></div> Now we can refer to the div’s id in our CSS, and style all the elements in that div in a uniform manner AJAX | Atul Kahate 20
  21. 21. <div> Example dummy.html<html><head> <link rel="stylesheet" type="text/css" href="dummy.css" /></head><body><p /><div id="menu"> <a href="home.html">home</a> <a href="books.html">writing</a> <a href="links.html">links</a> <a href="lib.html">lib</a></div></body></html> dummy.css#menu { font-family: Verdana; AJAX | Atul Kahate 21 font-color: red; background-color: silver;
  22. 22. <div> and <span> - 2 <span> allows individual element formatting better<ul> <li><span class=“books”>Books</span></li> <li><span class=“cd”>CDs</span></li> <li><span class=“cd”>DVDs</span></li></ul> AJAX | Atul Kahate 22
  23. 23. <span> Example dummy.html modified <html> <head> <link rel="stylesheet" type="text/css" href="dummy.css" /> </head> <body> <p /> AJAX | Atul Kahate 23
  24. 24. Step 2: Tell the object where tosend the request (Open theXMLHttpRequest Object)
  25. 25. Open the XMLHttpRequestObject – 1 Opening the XMLHttpRequest object prepares it for use to fetch data from the server Use the open method Mandatory parameters Method type (GET, PUT, POST) URL AJAX | Atul Kahate 25
  26. 26. Open the XMLHttpRequestObject – 2 Add a form with a Display Message button connected to a JavaScript function named getData To prepare for fetching data from the server, pass 1. The name of a text file (data.txt) to this function 2. Also pass the ID of the <div> element where results should be displayed, which is targtDiv Create the getData function and add an if statement to check if the XMLHttpRequest object has been created Open the XMLHttpRequest object, passing the open Get HTTP method, and the name of the file on the server to be opened AJAX | Atul Kahate 26
  27. 27. Open the XMLHttpRequestObject – 3 Final code (2.html) <!-- 2.html --> <html> <head> <title>AJAX Example 2</title> <script language = "javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } if (XMLHttpRequestObject) { document.write ("<h2>Welcome to AJAX</h2>"); } function getData (divID, dataSource) { alert ("Hello"); if (XMLHttpRequestObject) { var obj = document.getElementById (divID); XMLHttpRequestObject.open ("GET", dataSource); obj.innerHTML = "Object opened"; } } </script> </head> <!-- Add a form with a Display Message button connected to a JavaScript function named getData --> <body> AJAX | Atul Kahate 27 <H1>Fetching data with AJAX</H1>
  28. 28. Step 3: What to do when therequest is answered (Get Readyto Download)
  29. 29. Downloading Data from Server–1 We can download data from the server using the XMLHttpRequest object Happens ‘behind the scenes’, in an asynchronous manner When data comes from the server: The readyState property of the HTTPRequestObject changes to one of the following possible values: 0 – Uninitialized, 1 – Loading, 2 – Loaded, 3 – Interactive, 4 – Complete The status property holds the results of the HTTP download 200 – OK, 404 – Not found, etc AJAX | Atul Kahate 29
  30. 30. Handling AsynchronousRequests To handle the response received from asynchronous requests, we need to define a callback function For this, associate a function with the XMLHttpRequest object’s onReadyStateChange property like this: request.onreadystatechange = myFunction, where myFunction is a function that would deal with the response; Trouble is that with this approach, we cannot pass parameters to the function Alternate syntax is to use closures (an linline JavaScript function) like this: request.onreadystatechange = function () { myFunction (request) }; Now, we can pass whatever parameters to the callback function as we like AJAX | Atul Kahate 30
  31. 31. Downloading Data from Server–2 3.html <!-- 3.html --> <html> <head> <title>AJAX Example 3</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getData(divID, dataSource) { if (XMLHttpRequestObject) { alert ("Hello"); var obj = document.getElementById (divID); XMLHttpRequestObject.open ("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { obj.innerHTML = "Ready to download"; } } XMLHttpRequestObject.send (null); } } </script> </head> AJAX | Atul Kahate 31 <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
  32. 32. XmlHttpRequest ObjectProperties and Methods AJAX | Atul Kahate 32
  33. 33. Properties and Methods – 1Property/Method DescriptionreadyState Integer indicating the state of the request: 0 = Uninitialized, 1 = Loading, 2 = Response headers received, 3 = Some response body received, 4 = Request completeonreadystatechange Function to call whenever the readyState changesstatus HTTP status code returned by the server, such as 200, 404, etcstatusText Full status line returned by the server (eg “OK, No content”)responseText Full server response as a stringresponseXML Server’s response as an XML in the form of a Document objectabort () Cancels a request AJAX | Atul Kahate 33
  34. 34. Properties and Methods – 2Property/Method DescriptiongetAllResponseHeade Gets all headers in a name/value formatrs ()getResponseHeader Returs header value corresponding to a specified header(header name) nameopen (method, url, Initializes the request for sending to the serverasynch)setRequestHeader Adds an HTTP header to the request with a specified value(name, value)send (body) Initiates the request to the server AJAX | Atul Kahate 34
  35. 35. Step 4: Tell the object to make arequest (Download Data with theXMLHttpRequest Object)
  36. 36. Download Data with theXMLHttpRequest Object – 1 Using the open method, configure the XMLHttpRequest object to fetch a file named data.txt from the server When the button on the screen is clicked, a method named getData is called, to which to which the above file name is passed The getData function calls the open method on the XMLHTTPRequest object The open method opens the text file on the server using a GET method Later, we call the send method of the XMLHTTPRequest object to fetch data from this file, by passing a null value to it This method fetches data from the text file on to the browser It is made available inside the responseText property of the XMLHTTPRequest object We read that property and assign its value to <div> element Note: This page needs to be opened using a Web server URL (http://localhost:8080/ajax/4.html) when Tomcat is running AJAX | Atul Kahate 36
  37. 37. Download Data with theXMLHttpRequest Object – 2 <!-- 4.html --> <html> <head> <title>AJAX Example 3</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getData(divID, dataSource) { if (XMLHttpRequestObject) { alert ("Hello"); var obj = document.getElementById (divID); XMLHttpRequestObject.open ("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseText); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 0)) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send (null); } } </script> </head> AJAX | Atul Kahate 37 <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
  38. 38. Using Absolute URLs
  39. 39. Using Absolute URLs – 1 We can also specify the absolute URL of a file while retrieving data from it from the server side AJAX | Atul Kahate 39
  40. 40. Using Absolute URLs – 2 <!-- 5.html --> <html> <head> <title>AJAX Example 5</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getData(divID, dataSource) { if (XMLHttpRequestObject) { alert ("Hello"); var obj = document.getElementById (divID); XMLHttpRequestObject.open ("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseText); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send (null); } } </script> </head> AJAX | Atul Kahate 40 <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
  41. 41. Using Server-side Code
  42. 42. Using Server-side Code – 1 Instead of reading data from a text file stored on the server, we can invoke a server-side program (e.g. a JSP) The AJAX-enabled HTML page calls the server-side program on the click of a button The server-side program returns text back to the HTML page, which gets displayed on the screen AJAX | Atul Kahate 42
  43. 43. Using Server-side Code – 2 <!-- 6.html --> <html> <head> <title>AJAX Example 6</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getData(divID, dataSource) { if (XMLHttpRequestObject) { alert ("Hello"); var obj = document.getElementById (divID); XMLHttpRequestObject.open ("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseText); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send (null); } } </script> </head> AJAX | Atul Kahate 43 <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
  44. 44. The “X” of AJAX – Using XML
  45. 45. Using XML – 1 Create a button with caption Get sandwiches Write a new function getSandwiches, which gets called when the user clicks on this button This function downloads a simple XML file titled sandwiches.xml from the server The button is also connected to a drop-down list control to display sandwich types received from this XML Configure the XMLHTTPRequest object to fetch the sandwiches.xml file in the open method Add code to extract the contents of this XML file into a variable named xmlDocument, and add code to display a message Got the XML when the XML is succcessfully downloaded AJAX | Atul Kahate 45
  46. 46. Using XML – 2 <!-- 7.html --> <html> <head> <title>AJAX Example 7</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getSandwiches () { if (XMLHttpRequestObject) { alert ("Hello"); XMLHttpRequestObject.open ("GET", "sandwiches.xml"); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseXML); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { var xmlDocument = XMLHttpRequestObject.responseXML; document.write ("Got the XML"); } } XMLHttpRequestObject.send (null); } } </script> AJAX | Atul Kahate 46 </head>
  47. 47. Extracting Contents from anXML Document
  48. 48. Extracting Contents from anXML Document – 1 Extract an array of XML elements, such as sandwiches by using the getElementsByTagName method, and store that array in a variable named sandwiches Add the code to pass this sandwiches array variable to a new function, listSandwiches At this point, have the listSandwiches function only display a message Got the sandwiches Later, we will see how to extract the XML contents AJAX | Atul Kahate 48
  49. 49. Extracting Contents from anXML Document – 2 <!-- 8.html --> <html> <head> <title>AJAX Example 8</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getSandwiches () { if (XMLHttpRequestObject) { alert ("Hello"); XMLHttpRequestObject.open ("GET", "sandwiches.xml"); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseXML); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { var xmlDocument = XMLHttpRequestObject.responseXML; var sandwiches = xmlDocument.getElementsByTagName ("sandwich"); listSandwiches (sandwiches); document.write ("Got the XML"); } } AJAX | Atul Kahate 49 XMLHttpRequestObject.send (null); }
  50. 50. Extracting Data from XMLElements
  51. 51. Extracting Data from XMLElements – 1 We can extract data from XML elements by using JavaScript In our XML document, we have three sandwich elements inside the root element We want to extract these elements and display them on the HTML page AJAX | Atul Kahate 51
  52. 52. Extracting Data from XMLElements – 2 The text inside each XML element is considered as a text node Text node = Data item whose only content is text e.g. In<sandwich>cheese</sandwich>, the text node holds the text cheese To extract this text node, we need the syntax of sandwiches[i].firstChild The next step is to extract the actual text data from this text node. For this purpose, we need the syntax sandwiches[i].firstChild.data AJAX | Atul Kahate 52
  53. 53. Extracting Data from XMLElements – 3 Modify the listSandwiches function so that it: stores the drop-down list control in a variable named selectControl loops over all <sandwich> elements in the sandwiches array Add code to add <option> elements to the select control The select control’s options property holds an array of <option> elements inside the control, which display items in the control To create a new <option> object, use the JavaScript new operator Insert the expression to get the name of the current sandwich type We need to pass the text we want to appear in an <option> element to the option constructor method AJAX | Atul Kahate 53
  54. 54. Extracting Data from XMLElements – 4 <!-- 9.html --> <html> <head> <title>AJAX Example 9</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getSandwiches () { if (XMLHttpRequestObject) { alert ("Hello"); XMLHttpRequestObject.open ("GET", "sandwiches.xml"); XMLHttpRequestObject.onreadystatechange = function() { alert (XMLHttpRequestObject.readyState); alert (XMLHttpRequestObject.status); alert (XMLHttpRequestObject.responseXML); if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { var xmlDocument = XMLHttpRequestObject.responseXML; var sandwiches = xmlDocument.getElementsByTagName ("sandwich"); listSandwiches (sandwiches); } } XMLHttpRequestObject.send (null); } AJAX | Atul Kahate 54 }
  55. 55. Read Data Sent to the Server
  56. 56. Read Data Sent to the Server–1 We can write our scripts on the server to read data passed from the browser to the server Write a JSP page to return an XML document The HTML page provides two buttons to the user On click of the button, call the JSP page to retrieve the XML and display it on the screen AJAX | Atul Kahate 56
  57. 57. Read Data Sent to the Server–2 <!-- 10.html --> <html> <head> <title>AJAX Example 10</title> <script type = "text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } function getSandwiches1 () { if (XMLHttpRequestObject) { XMLHttpRequestObject.open ("GET", "ajax10.jsp?type=1"); XMLHttpRequestObject.onreadystatechange = function() { if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) { var xmlDocument = XMLHttpRequestObject.responseXML; var sandwiches = xmlDocument.getElementsByTagName ("sandwich"); listSandwiches (sandwiches); } } XMLHttpRequestObject.send (null); } } function getSandwiches2 () { if (XMLHttpRequestObject) { AJAX | Atul Kahate 57 XMLHttpRequestObject.open ("GET", "ajax10.jsp?type=2");
  58. 58. Read Data Sent to the Server–3 <% String param = request.getParameter ("type"); int type = 0; String [] sandwiches = new String [3]; if (param != null) { type = Integer.parseInt (param); } switch (type) { case 1: sandwiches [0] = "hot"; sandwiches [1] = "cold"; sandwiches [2] = "frozen"; break; case 2: sandwiches [0] = "veg"; sandwiches [1] = "jam"; sandwiches [2] = "cheese"; break; } response.setContentType("text/xml"); out.println ("<?xml version="1.0"?>"); out.println ("<sandwiches>"); for (int i=0; i<3; i++) { out.println ("<sandwich>"); out.println (sandwiches [i]); out.println ("</sandwich>"); } out.println ("</sandwiches>"); %> AJAX | Atul Kahate 58
  59. 59. Using MultipleXMLHttpRequest Objects
  60. 60. When is this needed? If multiple operations (e.g. buttons) use the same XMLHttpRequest object, this can cause confusion For example, user may get impatient and click on two buttons – one after the other – quickly; and if both buttons cause the same XMLHttpRequest object to be referred to, we have a problem Solution: Use multiple XMLHttpRequest objects Ref: D:tomcatwebappsexamplesajaxmultipleXMLHttpR equest AJAX | Atul Kahate 60
  61. 61. 11.html <html> <head> <title>Using two XMLHttpRequest Objects</title> <script type = "text/javascript"> var menu; var XMLHttpRequestObject1 = false; // alert ("start"); if (window.XMLHttpRequest) { XMLHttpRequestObject1 = new XMLHttpRequest (); XMLHttpRequestObject1.overrideMimeType ("text/xml"); // alert ("first"); } else if (window.ActiveXObject) { XMLHttpRequestObject1 = new ActiveXObject ("Microsoft.XMLHTTP"); } var XMLHttpRequestObject2 = false; if (window.XMLHttpRequest) { XMLHttpRequestObject2 = new XMLHttpRequest (); XMLHttpRequestObject2.overrideMimeType ("text/xml"); // alert ("second"); } else if (window.ActiveXObject) { XMLHttpRequestObject2 = new ActiveXObject ("Microsoft.XMLHTTP"); } function getMenu1 () { if (XMLHttpRequestObject1) { XMLHttpRequestObject1.open ("GET", "menu1.xml"); XMLHttpRequestObject1.onreadystatechange = function () { AJAX | Atul Kahate if (XMLHttpRequestObject1.readyState == 4 && XMLHttpRequestObject1.status == 200) { 61 var xmlDocument = XMLHttpRequestObject1.responseXML; menu = xmlDocument.getElementsByTagName ("menuitem");
  62. 62. menu1.xml <?xml version = "1.0"?> <menu> <menuitem>Main course</menuitem> <menuitem>Fasting</menuitem> <menuitem>Salad and Fruits</menuitem> </menu> AJAX | Atul Kahate 62
  63. 63. menu2.xml <?xml version = "1.0"?> <menu> <menuitem>Tomato</menuitem> <menuitem>Cheese</menuitem> <menuitem>Cucumber</menuitem> </menu> AJAX | Atul Kahate 63
  64. 64. Ajax Calculator Write a simple Ajax application to accept two integers from the user and display their sum on the same screen NetBeans - AjaxCalculator
  65. 65. index.html <html> <head> <title>Ajax Multiplier</title> <link rel = "stylesheet" type="text/css" href="calc.css" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/JavaScript" src="ajax.js"></script> </head> <body> <form name = "the_form"> <h1>Ajax Multiplier</h1> <br><br> <h3>Enter integer values below</h3> <br><br> <table> <tr> <td>Value 1</td> <td><input type="text" id = "field_1"></td> </tr> <tr> <td>Value 2</td> <td><input type="text" id = "field_2"></td> </tr> <tr> <td align="center"> <input type = "button" id = "submit" value = "Multiply" onclick="multiplyThem();return false;"> </td> </tr> </table> <br> <br> AJAX | Atul Kahate 65 <table>
  66. 66. calc.css /* Document : calc Created on : Nov 19, 2007, 5:20:41 PM Author : atulk Description: Purpose of the stylesheet follows. */ /* TODO customize this sample style Syntax recommendation http://www.w3.org/TR/REC-CSS2/ */ h1 { text-align: center; color: blue; font-weight: lighter; font-family: fantasy; clip: rect(0px, 0px, 0px, 0px); letter-spacing: 3px; } td { font-family: Courier New,Courier,monospace; font-size: 14px; background-color: #ffffcc; } input { font-family: cursive; font-size: 14px; } table { border-right-style: groove; border-left-style: groove; AJAX | Atul Kahate 66 border-bottom-style: groove; border-top-style: groove;
  67. 67. ajax.js var req; function multiplyThem () { var num_1 = document.the_form.field_1.value; var num_2 = document.the_form.field_2.value; var url = "MultiplyNumbersServlet?num_1=" + escape (num_1) + "&num_2=" + escape (num_2); if (window.XMLHttpRequest) { req = new XMLHttpRequest (); } else if (window.ActiveXObject) { req = new ActiveXObject ("Microsoft.XMLHTTP"); } req.open ("get", url, true); req.onreadystatechange = callback; req.send (null); } function callback () { if (req.readyState == 4) { if (req.status == 200) { var servlet_response = req.responseText; // alert (servlet_response); document.the_form.result.value = servlet_response; } } } AJAX | Atul Kahate 67
  68. 68. MultiplyNumbersServlet.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ajax.servlet; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; /** * * @author atulk */ public class MultiplyNumbersServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/text"); PrintWriter out = response.getWriter(); String num_1_str = request.getParameter("num_1"); String num_2_str = request.getParameter("num_2"); System.out.println(num_1_str); System.out.println(num_2_str); try { int num_1 = Integer.parseInt(num_1_str); int num_2 = Integer.parseInt(num_2_str); out.print(num_1 * num_2); } catch (java.lang.NumberFormatException e) { e.printStackTrace(); out.print("--- NUMBER ERROR ---"); } } AJAX | Atul Kahate 68 }
  69. 69. Modify Ajax Calculator AJAX | Atul Kahate 69
  70. 70. Changes to be done Now allow all operations (add, subtract, multiply, divide) AJAX | Atul Kahate 70
  71. 71. index-2.html Ajax Calculator Enter integer values below Value 1 Value 2 Operation (+ - * or /) Result AJAX | Atul Kahate 71
  72. 72. ajax-2.js var req; function computeResult () { var num_1 = document.the_form.field_1.value; var num_2 = document.the_form.field_2.value; var operator = AJAX | Atul Kahate 72 document.the_form.field_3.value;
  73. 73. AllOperationsServlet /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ajax.servlet; import java.io.*; | Atul Kahate AJAX 73 import java.net.*;
  74. 74. AJAX Application Character Decoder – Allow the user to enter a character and show its ASCII value (Netbeans – AJAX-Character-Decoder-1)
  75. 75. index.html <html> <head> <link rel = "stylesheet" type="text/css" href="style.css" /> <script language="JavaScript" src="ajax.js"></script> <title>Ajax with Java</title> </head> <body onload="focusIn ();"> <h1>Ajax Character Decoder</h1> <h2>Press a key to find its value ...</h2> <table> <tr> <td>Enter key Here -> <input type = "text" id="key" name="key" onkeyup="convertToDecimal ();"> </td> </tr> </table> <br /> <table> <tr> <td colspan = "5" style="border-bottom: solid black 1px;"> Key pressed: <input type="text" readonly id = "keypressed"> </td> </tr> <tr> <td>Decimal</td> </tr> <tr> <td> <input type = "text" readonly id="decimal"> </td> </tr> </table> AJAX | Atul Kahate 75 </body>
  76. 76. ajax.js var req; function convertToDecimal () { var key = document.getElementById ("key"); var keypressed = document.getElementById ("keypressed"); keypressed.value = key.value; alert (keypressed.value); var url = "AjaxResponseServlet?key=" + escape (key.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest (); } else if (window.ActiveXObject) { req = new ActiveXObject ("Microsoft.XMLHTTP"); } req.open ("get", url, true); req.onreadystatechange = callback; req.send (null); } function callback () { alert ("readyState = " + req.readyState); alert ("status = " + req.status); if (req.readyState == 4) { if (req.status == 200) { var decimal = document.getElementById (decimal); decimal.value = req.responseText; } } clear (); } AJAX | Atul Kahate 76 function clear () { var key = document.getElementById ("key");
  77. 77. style.css body { font-family: Arial, Helvetica, sans-serif; font-size: small; text-align: center; background: #cbdada; } #keypressed { width: 30; border: none; } #key { width: 20px; padding: 0; margin: 0; border: none; text-align: left; } h1, h2 { font-size: 120%; text-align: center; } h2 { font-size: 110%; } table, input { margin-left: auto; margin-right: auto; padding: 0px 10px; text-align: center; color: black; background: #a0f6f5; border: solid black 1px; } AJAX | Atul Kahate 77 td {
  78. 78. AjaxResponseServlet.java /* * AjaxResponseServlet.java * * Created on September 21, 2007, 2:58 PM */ package com.ajax.servlet; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; /** * * @author AtulK * @version */ public class AjaxResponseServlet extends HttpServlet { public static final long serialVersionUID = 1L; // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Inside servlet"); String key = request.getParameter("key"); System.out.println("Key = " + key); if (key != null) { AJAX | Atul Kahate 78 // Extract first character from key as int, and convert it into a string int keychar = key.charAt(0);
  79. 79. web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>AjaxResponseServlet</servlet-name> <servlet-class>com.ajax.servlet.AjaxResponseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxResponseServlet</servlet-name> <url-pattern>/AjaxResponseServlet</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app> AJAX | Atul Kahate 79
  80. 80. Exercise Modify the above example to allow the user to type. As soon as the user types a character, get all the matching entries starting with that character and display back to the user NetBeans: Ajax-Character-Decoder-2 AJAX | Atul Kahate 80
  81. 81. index.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel = "stylesheet" type="text/css" href="style.css" /> <script type="text/JavaScript" src="ajax.js"></script> <title>Ajax with Java</title> </head> <body onload="focusIn ();"> <h1>Get Matching Values from the Database</h1> <p><p> <h2>Press a key to get matching values ...</h2> <table> <tr> <td>Enter key Here -> <input type = "text" id="key" name="key" onkeyup="getMatchingValues ();"> </td> </tr> </table> <br /> <table> <tr> <td> Key pressed: <input type="text" readonly id = "keypressed"> </td> </tr> <tr> <td>Matching values</td> </tr> <tr> <td> AJAX | Atul Kahate <input type = "text" id = "decimal" readonly value = ""> 81 </td> </tr>
  82. 82. style.css body { font-family: Arial, Helvetica, sans-serif; font-size: small; text-align: center; background: #cbdada; } h1, h2 { font-size: 120%; text-align: center; } h2 { font-size: 110%; } table, input { margin-left: auto; margin-right: auto; padding: 0px 10px; text-align: center; color: black; background: #a0f6f5; border: solid black 1px; } td { margin: 10px; padding: 0px 5px; border: none; } input { width: 300; border: none; border-top: solid #999999 1px; font-size: 80%; color: #555555; AJAX | Atul Kahate 82 }
  83. 83. ajax.js var req; function getMatchingValues () { // decimal.clear (); var key = null; key = document.getElementById ("key"); var keypressed = document.getElementById ("keypressed"); keypressed.value = key.value; // alert (keypressed.value); var url = "AjaxResponseServlet?key=" + escape (key.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest (); } else if (window.ActiveXObject) { req = new ActiveXObject ("Microsoft.XMLHTTP"); } req.open ("get", url, true); req.onreadystatechange = callback; req.send (null); } function callback () { // alert ("readyState = " + req.readyState); // alert ("status = " + req.status); if (req.readyState == 4) { if (req.status == 200) { var decimal = document.getElementById (decimal); // alert (req.responseText); decimal.value = req.responseText; } AJAX | Atul Kahate 83 } clear ();
  84. 84. AjaxResponseServlet.java /* * AjaxResponseServlet.java * * Created on September 21, 2007, 2:58 PM */ package com.ajax.servlet; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.util.*; /** * * @author AtulK * @version */ public class AjaxResponseServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String key = request.getParameter("key"); System.out.println("Key = " + key); List userIds = new ArrayList (); if (!key.equals("")) { try { Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/users"); ResultSet rs = null; AJAX | Atul Kahate 84 PreparedStatement ps = con.prepareStatement("SELECT user_id FROM user_table WHERE user_id like ? ");
  85. 85. Account Balance Example NetBeans Ajax-Misc AJAX | Atul Kahate 85
  86. 86. Requirements User types an account number. Show corresponding account balance. Also show one of the following messages: Success Account number is invalid Error in processing AJAX | Atul Kahate 86
  87. 87. getAccountDetails.html Account Details Enter acocunt details Account Number Account Balance Status AJAX | Atul Kahate 87
  88. 88. account.js var req; function getAccountDetails () { var accountNumber = document.the_form.field_1.value; // alert ("inside JS"); AJAX | Atul Kahate 88 var url =
  89. 89. getAccountDetails.jsp <%@ page import="java.util.*" %> <%@ page import="com.ajax.serverside.Account" %> <% String accountNumber = request.getParameter ("accountNumber"); Kahate AJAX | Atul 89
  90. 90. Account.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ajax.serverside; AJAX | Atul Kahate 90 /**
  91. 91. Case Study – Building an AJAXApplication
  92. 92. Requirements We have a book shop, where we want to constantly view the amount of profit we have made For this purpose, the server-side code sends us the latest number of copies sold, as on date We multiply that with the profit per copy (sale price less purchase price), and compute the total profit made AJAX | Atul Kahate 92
  93. 93. Traditional ApplicationExample Web form that JSP submits the returns request to a the latest JSP page number of copies sold AJAX | Atul Kahate 93
  94. 94. Execution Steps – 1 User clicks here AJAX | Atul Kahate 94
  95. 95. Execution Steps – 2 Reload! Server sends a response now AJAX | Atul Kahate 95
  96. 96. Code for the AJAX Version Several basic concepts are needed to understand this, and hence, we shall study it after the theoretical and conceptual overview Come back to the next slide later, once the basic concepts are finished AJAX | Atul Kahate 96
  97. 97. Application Design Our code would have the following JavaScript functions: getBooksSold () Would create a new object to talk to the server updatePage () Would ask the server for the latest book sales figures createRequest () Set the number of books sold and profit made AJAX | Atul Kahate 97
  98. 98. The HTML Part(d:tomcatwebappsexamplesAJAXbooks.html)<html> <head> <title>Sales Report</title> <link rel="stylesheet" type="text/css" href="books.css" /></head> <body> <h1>Sales Report for our Books</h1> <div id="Books"> <table> <tr><th>Books Sold</th> <td><span id="books-sold">555</span></td></tr> <tr><th>Sell Price</th> <td>Rs. <span id="price">300</span></td></tr> <tr><th>Buying Cost</th> <td>Rs. <span id="cost">250</span></td></tr> </table> <h2>Profit Made: Rs. <span id="cash">27750</span></h2> <form method="GET" action="getUpdatedBookSales.jsp"> <input value="Show me the latest profit" type="button" /> </form> </div> </body></html> AJAX | Atul Kahate 98
  99. 99. Add JavaScript Now On click of the button, call a JavaScript function getBooksSold () AJAX | Atul Kahate 99
  100. 100. The getBooksSold () Function Create a new request by calling the createRequest () function Specify the URL to receive the updates from Set up the request object to make a connection Request an updated number of books sold AJAX | Atul Kahate 100
  101. 101. JavaScript Code Outline<script language=“javascript” type=“text/javascript”> function createRequest () // JavaScript code function getBooksSold () createRequest ();</script> AJAX | Atul Kahate 101
  102. 102. createRequest () Function This function would simply try to create an instance of the XMLHttpRequest object, as per the browser typefunction createRequest () { if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest (); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP"); } } AJAX | Atul Kahate 102
  103. 103. Now Modify getBooksSold ()function getBooksSold () { createRequest (); var url = "getUpdatedBookSales.jsp"; XMLHttpRequestObject.open ("GET", url); … This would call getUpdatedBookSales.jsp We want to process the response sent by this JSP now AJAX | Atul Kahate 103
  104. 104. Now, Process the Resultsfunction getBooksSold () { createRequest (); var url = "getUpdatedBookSales.jsp"; XMLHttpRequestObject.open ("GET", url); XMLHttpRequestObject.onreadystatechange = updatePage; XMLHttpRequestObject.send (null); How does this work? AJAX | Atul Kahate 104
  105. 105. updatePage ( ) Needs to dothis Updated number of books sold JavaScript Update these now AJAX | Atul Kahate 105
  106. 106. When to call updatePage ()? When this function receives a response from JSP, it needs to update the values on the screen, making this asynchronous Hence, we have: XMLHttpRequestObject.onreadystatechang e = updatePage; Call updatePage () when a response is received AJAX | Atul Kahate 106
  107. 107. updatePage () Function – 1 First read the response sent by the JSP pagefunction updatePage () { var newTotal = XMLHttpRequestObject.responseText; This would read the updated values of books sold to date from the server-side into a JavaScript variable called as newTotal AJAX | Atul Kahate 107
  108. 108. updatePage () Function – 2function updatePage () { var newTotal = XMLHttpRequestObject.responseText; var booksSoldElement = document.getElementById ("books-sold"); var cashElement = document.getElementById ("cash"); Now, read the current values of the HTML elements books-sold and cash into two JavaScript variables We want to update these on the screen AJAX | Atul Kahate 108
  109. 109. updatePage () Function – 3function updatePage () { var newTotal = XMLHttpRequestObject.responseText; var booksSoldElement = document.getElementById ("books-sold"); var cashElement = document.getElementById ("cash"); replaceText (booksSoldElement, newTotal); This is our own function, which will replace the current HTML element’s value with the updated one, on the screen AJAX | Atul Kahate 109
  110. 110. What should the JSP do? Normally, the JSP would return a full HTML Now, it has to return a single number: number of books sold at this moment Hence, the JSP just has: out.print (300); AJAX | Atul Kahate 110
  111. 111. Want to see how it reallyworks? Change the JSP to introduce delays<% for (int i=1; i<40000; i++) { for (int j=1; j<40000; j++); } for (int i=1; i<40000; i++); for (int i=1; i<40000; i++); out.print ("300");%> Now rerun the application AJAX | Atul Kahate 111
  112. 112. Modify the example to expectan XML from the JSP D:tomcatwebappsajaxbooks- xml-version AJAX | Atul Kahate 112
  113. 113. Initial Screen AJAX | Atul Kahate 113
  114. 114. Requirements – 1 When the user clicks on the button, the browser should send a request to the JSP as before The JSP would now send an XML document, containing the following: <?xml version="1.0"?> <total-sale> <complete-reference-books>20</complete-reference-books> <professional-books>35</professional-books> <head-first-books>15</head-first-books> </total-sale> AJAX | Atul Kahate 114
  115. 115. Requirements – 2 - Result AJAX | Atul Kahate 115
  116. 116. books.html <html> <head> <title>Sales Report</title> <link rel="stylesheet" type="text/css" href="books.css" /> <script language = "javascript" type = "text/javascript"> AJAX | Atul Kahate 116
  117. 117. getUpdatedBookSales.jsp <% response.setContentType("text/xml") ; out.println ("<?xml version="1.0"?>"); out.println ("<total-sell>"); AJAX | Atul Kahate 117
  118. 118. books.css body { font-family: Verdana; } h1 { background-color: silver; } AJAX | Atul Kahate 118 h2 {
  119. 119. User ID – Case Study NetBeans – Ajax-Misc AJAX | Atul Kahate 119
  120. 120. Requirements Accept a user ID from the user for new ID creation If it is free, accept user name and allow user to create/cancel a new user If it is already taken, show an error message and allow to choose another ID AJAX | Atul Kahate 120
  121. 121. checkUserID.html User ID Details Enter user ID details User ID Status AJAX | Atul Kahate 121
  122. 122. user.css /* Document : user Created on : Jun 9, 2008, 2:30:51 PM Author : atulk Description: Purpose of the stylesheet follows. */ AJAX | Atul Kahate 122
  123. 123. user.js var req; function getUserID () { var userID = document.the_form.field_1.value; // alert ("inside JS"); AJAX | Atul Kahate 123 var url = "getUserID.jsp?userID=" +
  124. 124. getUserID.jsp <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.ajax.serverside.User" %> <% String userID = request.getParameter("userID"); AJAX | Atul Kahate 124 ResultSet rs = null;
  125. 125. createNewUser.jsp <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="com.ajax.serverside.User" %> <% String userID = request.getParameter("userID"); AJAX | Atul Kahate 125 String userName =
  126. 126. JSON (JavaScript ObjectNotation) AJAX | Atul Kahate 126
  127. 127. What is JSON? Alternative to XML when we do not need advanced capabilities of XML, such as validations, formatting using XSLT, etc When we use XML as a simple means of transmitting data between two points, we can use JSON instead of XML AJAX | Atul Kahate 127
  128. 128. JSON Advantages JSON is lightweight Data represented in JSON is quite concise Like XML, JSON is also human-readable (but not to the level of XML) Performance when parsing JSON is quite good JSON can be recognized and parsed by JavaScript alone unlike XML, where we need special APIs to deal with XML AJAX | Atul Kahate 128
  129. 129. JSON Technical Details JSON is a small subset of the JavaScript language, aimed at representing structured data. This means that we need to follow certain JavaScript syntax, which enables us to deal with the following constructs: Objects – These are unordered sets of name/value pairs. They start and end with the { and } symbols, respectively. Arrays – These are ordered collections of values. They start and end with the [ and ] symbols, respectively. Values – These are strings, numbers, Boolean values, nested objects, arrays, etc. AJAX | Atul Kahate 129
  130. 130. XML Versus JSON <?xml version=”1.0”?> { “books”: [ <books> { “book”: { “title”: “Computer Networks”, <book> “author”: “Andrew Tanenbaum”}}, <title>Computer Networks</title> { “book”: { “title”: “TCP/IP”, <author>Andrew Tanenbaum</author> “author”: “Douglas Comer”}}, </book> { “book”: { “title”: “C: The Complete Reference”, <book> “author”: “Andrew Tanenbaum”}} <title>TCP/IP</title> ] <author>Douglas Comer</author> } </book> <book> <title>C: The Complete Reference</title> <author>Herbert Schildt</author> XML JSON </book> </books> AJAX | Atul Kahate 130
  131. 131. Creating JSON on the Server(in Java) String myString = new JSONObject().put (“title”, “TCP/IP”).toString (); This creates a Java String named myString, containing the value {“title”: “TCP/IP”}. We can add it to our JSON text. Later, we can parse this on the client-side, as shown next. AJAX | Atul Kahate 131
  132. 132. Parsing JSON in JavaScript How do we parse a JSON document? It is very simple, and can be accomplished by one line of JavaScript code: var result = eval (‘(‘ + jsonText + ‘)’); This statement parses the JSON text and produces a JavaScript- compatible object out of it. Once we have the parsed JSON document available to us as a JavaScript variable, the next steps are very easy: var thirdBookTitle = result.books[3].book.title; This would read the title of the third book of our JSON text and store it inside a JavaScript variable. AJAX | Atul Kahate 132
  133. 133. JSON Drawbacks While being less verbose than XML makes JSON faster, it can also become a drawback if we actually expect the content representation to be verbose There is no concept of namespaces in JSON, making the possibility of mixing contents from different sources seamlessly more difficult as compared to XML What are element-equivalent portions and what are attribute- equivalent portions in JSON is not very clear, in contrast to XML Creation and validation of JSON documents is more difficult as compared to XML AJAX | Atul Kahate 133
  134. 134. JSON Example (Same BooksExample now in JSON) D:tomcatwebappsajaxbooks- json-version AJAX | Atul Kahate 134
  135. 135. books.html <html> <head> <title>Sales Report</title> <link rel="stylesheet" type="text/css" href="books.css" /> <script language = "javascript" type = "text/javascript"> AJAX | Atul Kahate 135
  136. 136. getUpdatedBookSales.jsp <% out.println ("{"totalSale": ["); out.println ("{"); out.println (""completeReferenceBooks": 20,"); out.println (""professionalBooks": 136 AJAX | Atul Kahate 35,");
  137. 137. books.css body { font-family: Verdana; } h1 { background-color: silver; } AJAX | Atul Kahate 137 h2 {
  138. 138. Second Case Study – PizzaDelivery
  139. 139. Requirements User would type the phone number here. Once finished, the customer’s address details should be shown automatically. AJAX | Atul Kahate 139
  140. 140. Processing Steps1. Customer enters phone number.2. A JavaScript function gets called.3. This JavaScript function sends the customer’s phone number to the server and asks for the customer’s address.4. While the server is looking up for the customer’s address, the customer can enter order details.5. The browser calls a JavaScript function that updates the Web page in the browser with the customer’s address. AJAX | Atul Kahate 140
  141. 141. HTML for the Basic Page pizzaDelivery.html<html> <head> <title>Pizza Delivery Page</title> <link rel="stylesheet" type="text/css" href="pizzaDelivery.css" /> </head> <body> <form method="POST" action="placeOrder.jsp"> AJAX | Atul Kahate 141 <p>Enter your phone number:
  142. 142. CSS for the Basic Page pizzaDelivery.cssbody { font-family: Verdana; background-color: black;}p{ font-size: large; color: red;} AJAX | Atul Kahate 142textarea {
  143. 143. Event Handling We need to capture an event to know when the customer provides a phone number onChange – Gets called when the value in a form field changes (e.g. typing a new value or clearing an existing one) onFocus – Gets called when the user enters a field in the form onBlur – Gets called when the user leaves a field We would use onChange Modifying the form now … AJAX | Atul Kahate 143
  144. 144. Modified HTML Page <html> <head> <title>Pizza Delivery Page</title> <link rel="stylesheet" type="text/css" href="pizzaDelivery.css" /> </head> <body onLoad="document.forms[0].reset();"> AJAX | Atul Kahate 144 <form method="POST"
  145. 145. Writing the getCustomerInfo() Function – 1 We need to obtain the value of the phone number entered by the userfunction getCustomerInfo () { var phone = document.getElementById (“phone”).value; AJAX | Atul Kahate 145
  146. 146. Writing the getCustomerInfo() Function – 2 Next, we want to request for the customer’s address 1. Create a request object. 2. Send the request, containing the phone number to the server. 3. Write the server-side code to process this request. AJAX | Atul Kahate 146
  147. 147. Writing the getCustomerInfo() Function – 3function getCustomerInfo ( ) { var phone = document.getElementById (“phone”).value; var url = “lookupCustomer.jsp?phone=“ + escape (phone); request.open (“GET”, url, true); request.onreadystatechange = updatePage; request.send (null);} AJAX | Atul Kahate 147
  148. 148. Full HTML(C:tomcatwebappsexamplesAJAXpizza) <html> <head> <title>Pizza Delivery Page</title> <link rel="stylesheet" type="text/css" href="pizzaDelivery.css" /> <script language = "javascript" type = "text/javascript"> AJAX | Atul Kahate 148 var XMLHttpRequestObject = null;
  149. 149. JSP Page <% for (int i=1; i<30000; i++) for (int j=1; j<30000; j++) for (int k=1; k<5; k++); out.print ("Pune"); %> AJAX | Atul Kahate 149
  150. 150. Exercise Modify the JSP page to read the address from a database AJAX | Atul Kahate 150
  151. 151. Modified JSP <%@page import="java.sql.*" %> <%@page import="java.util.*" %> <% // Open Database Connection Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); // Open a connection to the database Connection con Atul Kahate AJAX | = 151 DriverManager.getConnection("jdbc:odbc:cust
  152. 152. Another Case Study – CoffeeMaker
  153. 153. User Interface Coffee Maker Coffee Maker #1 #2 Idle Idle Place your coffee order here: ame: ________________________ Size Small O Medium O Large O Beverage Mocha O Black Coffee O Filter Coffee O Order Coffee AJAX | Atul Kahate 153
  154. 154. Requirements Initially, both Coffee Maker #1 and #2 would be idle Whenever anyone submits an order for coffee, Maker#1 comes into action, and needs some time to make coffee During this time if another order comes, it needs to be processed by Maker #2 AJAX | Atul Kahate 154
  155. 155. Application Structure Coffee maker HTML Take orders, report status of the two makers JavaScript code Create a request object, a function to send order to the coffee-making script, serve a drink when ready, Event handlers to connect the form buttons to JavaScript functions Server-side code Coffee-making script when an order is placed, should be able to handle two requests at a time AJAX | Atul Kahate 155
  156. 156. Application Flow – 1 The Web page should display the status of both coffee makers (Idle initially) Coffee Coffee Maker #1 Maker #2 Idle Idle Place your coffee order here: ame: ________________________ Size Small O Medium O Large O Beverage Mocha O Black Coffee O Filter Coffee O Order Coffee AJAX | Atul Kahate 156
  157. 157. Application Flow – 2 <!– Server side code for coffee making --> <% if … %> … Coffee Coffee <script> Maker #1 Maker #2 Var XmlHttp … Idle Idle … The JavaScript should be Place your coffee order here: able to send requests to ame: ________________________ brew coffee to the coffee Size maker script on the server and handle response Small O Medium O Large O received from the server. It also needs to update Beverage the status of the coffee maker, and let the users Mocha O Black Coffee O Filter Coffee O know when the coffee is Order Coffee ready. AJAX | Atul Kahate 157
  158. 158. Application Flow – 3 <!– Server side code for coffee making --> <% if … %> … Coffee Coffee <script> Maker #1 Maker #2 Var XmlHttp … Idle Idle … The server-side code is quite Place your coffee order here: simple. It takes a request to ame: ________________________ brew coffee along with the Size cup size, coffee type, and name of the person. Once the Small O Medium O Large O coffee is ready, it sends back the response along with the Beverage name of the person who placed the order. Mocha O Black Coffee O Filter Coffee O Order Coffee AJAX | Atul Kahate 158
  159. 159. Sample Flow – 1 <!– Server side code for coffee making --> <% if … %> … Coffee Coffee <script> Maker #1 Maker #2 Var XmlHttp … Idle Idle … Sachin has placed an order for Place your coffee order here: small coffee of mocha type. ame: __Sachin_____________________ This should cause the Size JavaScript code to send a request to the server-side for Small Medium O Large O making this type of coffee. This order would be placed to Beverage Coffee Maker #1. Mocha Black Coffee O Filter Coffee O Order Coffee AJAX | Atul Kahate 159
  160. 160. Sample Flow – 2 <!– Server side code for coffee making --> <% if … %> … Coffee Coffee <script> Maker #1 Maker #2 Var XmlHttp … Busy Idle … While Sachin’s order is being Place your coffee order here: processed, Rahul wants to ame: __Rahul_____________________ order a filter coffee of medium Size size. Since this is an asynchronous application, it Small O Medium Large O should allow Rahul to place his order. Rahul’s order will go Beverage to Coffee Maker #2. We have updated the status of Coffee Mocha O Black Coffee O Filter Coffee Maker#1, though. Order Coffee AJAX | Atul Kahate 160
  161. 161. Sample Flow – 3 <!– Server side code for coffee making --> <% if … %> … Coffee Coffee <script> Maker #1 Maker #2 Var XmlHttp … Idle Idle … When Sachin’s coffee is ready, Place your coffee order here: we send a message from the ame: ________________________ server-side code to indicate so. Also, the status of Coffee Sachin: Your coffee is ready! Size Maker #1 is changed back to Small O Medium O Large O Idle, indicating that it is ready to take a fresh order. Beverage Mocha O Black Coffee O Filter Coffee O Order Coffee AJAX | Atul Kahate 161
  162. 162. Thank you! Any Questions?

×