Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ajax Dr. Reda Salama. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better,

Similar presentations


Presentation on theme: "Ajax Dr. Reda Salama. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better,"— Presentation transcript:

1 Ajax Dr. Reda Salama

2 The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better, faster, more responsive web applications” These changes are so sweeping that the Ajax-enabled web is sometimes know as “Web 2.0” The term Ajax was coined by Jesse James Garrett of Adaptive Path in February 2005, when he was presenting the previously unnamed technology to a client Ajax technologies (XHTML, JavaScript, CSS, dynamic HTML, the DOM and XML) have existed for many years. Web applications with Ajax were supposed to replace all our traditional desktop applications. It was a DREAM 2

3 The Dream: Make Web looks like Desktop desktop application characteristic (Spreadsheet app, etc.) responses intuitively and quickly gives a user meaningful feedback's instantly A cell in a spreadsheet changes color when you hover your mouse over it Icons light up as mouse hovers them Things happen naturally. No need to click a button or a link to trigger an event Web Application characteristic “Click, wait, and refresh” user interaction Page refreshes from the server needed for all events, data submissions, and navigation Synchronous “request/response” communication model > The user has to wait for the response 3

4 The reality Ajax is a technique for creating “better, faster, more responsive web applications” But they still aren’t as responsive as desktop applications, and probably never will be Web applications are useless when you aren’t on the web GUIs are HTML forms (and you know how beautiful and flexible those are) The technology has been available for some time Nevertheless, Ajax is the “hot new thing” because: Google uses it extensively, in things like Google Earth and Google Suggest It has been given a catchy name Ajax is a useful technology, and a good thing to have on your resumé 4

5 Example 5

6 6 Ajax Issues Usability of web applications has lagged behind compared to desktop applications Rich Internet Applications (RIAs) Web applications that approximate the look, feel and usability of desktop applications Two key attributes—performance and rich GUI RIA performance Comes from Ajax (Asynchronous JavaScript and XML), which uses client-side scripting to make web applications more responsive Ajax applications separate client-side user interaction and server communication, and run them in parallel, making the delays of server-side processing more transparent to the user “Raw” Ajax uses JavaScript to send asynchronous requests to the server, then updates the page using the DOM When writing “raw” Ajax you need to deal directly with cross- browser portability issues, making it impractical for developing large-scale applications

7 7 Ajax Issues (Cont.) Portability issues Hidden by Ajax toolkits, such as Dojo, Prototype and Script.aculo.us Toolkits provide powerful ready-to-use controls and functions that enrich web applications and simplify JavaScript coding by making it cross-browser compatible Achieve rich GUI in RIAs with Ajax toolkits RIA environments such as Adobe’s Flex, Microsoft’s Silverlight and JavaServer Faces Such toolkits and environments provide powerful ready-to-use controls and functions that enrich web applications. Client-side of Ajax applications Written in XHTML and CSS Uses JavaScript to add functionality to the user interface XML is used to structure the data passed between the server and the client XMLHttpRequest The Ajax component that manages interaction with the server Commonly abbreviated as XHR.

8 8 Traditional Web Applications vs. Ajax Applications Traditional web applications User fills in the form’s fields, then submits the form Browser generates a request to the server, which receives the request and processes it Server generates and sends a response containing the exact page that the browser will render Browser loads the new page and temporarily makes the browser window blank Client waits for the server to respond and reloads the entire page with the data from the response While a synchronous request is being processed on the server, the user cannot interact with the client web browser The synchronous model was originally designed for a web of hypertext documents some people called it the “brochure web” model yielded “choppy” application performance

9 9 Traditional Web Applications (load entire)

10 10 Ajax-enabled Web Applications (load partial) In an Ajax application, when the user interacts with a page Client creates an XMLHttpRequest object to manage a request XMLHttpRequest object sends the request to and awaits the response from the server Requests are asynchronous, allowing the user to continue interacting with the application while the server processes the request concurrently When the server responds, the XMLHttpRequest object that issued the request invokes a callback function, which typically uses partial page updates to display the returned data in the existing web page without reloading the entire page Callback function updates only a designated part of the page Partial page updates help make web applications more responsive, making them feel more like desktop applications

11 11 Ajax-enabled web application interacting with the server asynchronously.

12 Traditional vs. AJAX Interface construction is mainly the responsibility of the server User interaction via form submissions An entire page is required for each interaction (bandwidth) Application is unavailable while an interaction is processing (application speed) Interface is manipulated by client-side JavaScript manipulations of the Document Object Model (DOM) User interaction via HTTP requests ‘behind the scenes’ Communication can be restricted to data only Application is always responsive 12

13 How Ajax works You do something with an HTML form in your browser JavaScript on the HTML page sends an HTTP request to the server The server responds with a small amount of data, rather than a complete web page JavaScript uses this data to modify the page?. How? One possibility through the DOM This is faster because less data is transmitted and because the browser has less work to do 13

14 Underlying technologies JavaScript XHTML CSS DOM XML/XSLT XML is often used for receiving data from the server Plain text can also be used, so XML is optional HTTP XMLHttpRequest Object that performs asynchronous interaction with the server All these are open standards 14

15 Starting from the browser… Your browser must allow JavaScript, or Ajax won’t work Otherwise, there’s nothing special required of the browser Your browser has some way of providing data to the server—usually from an HTML form JavaScript has to handle events from the form, create an XMLHttpRequest object, and send it (via HTTP) to the server Nothing special is required of the server—every server can handle HTTP requests Despite the name, the XMLHttpRequest object does not require XML because response can be sent also as html text 15

16 The XMLHttpRequest object JavaScript has to create an XMLHttpRequest object For historical reasons, there are three ways of doing this For most browsers, just do var request = new XMLHttpRequest(); For some versions of Internet Explorer, do var request = new ActiveXObject("Microsoft.XMLHTTP"); For other versions of Internet Explorer, do var request = new ActiveXObject("Msxml2.XMLHTTP"); Doing it incorrectly will cause an Exception The next slide shows a JavaScript function for choosing the right way to create an XMLHttpRequest object 16

17 Step1: Getting the XMLHttpRequest object- Alternative 1 var request = null; // we want this to be global function getXMLHttpRequest( ) { try { request = new XMLHttpRequest(); } catch(err1) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err2) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(err3) { request = null; } } } if (request == null) alert("Error creating request object!"); } 17

18 Step1: Getting the XMLHttpRequest object- Alternative 2 var req; function initRequest() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari req = new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } 18

19 Step 2: Preparing the XMLHttpRequest object Once you have an XMLHttpRequest object, you have to prepare it with the open method request.open( method, URL, asynchronous ) The method is usually 'GET' or 'POST ' The URL is where you are sending the data If using a 'GET', append the data to the URL If using a 'POST', add the data in a later step If asynchronous is true, the browser does not wait for a response (this is what you usually want) request.open( method, URL ) As above, with asynchronous defaulting to true 19

20 Step 3: Send the XMLHttpRequest object Once the XMLHttpRequest object has been prepared, you have to send it request.send(null); This is the version you use with a GET request request.send( content ); This is the version you use with a POST request The content has the same syntax as the suffix to a GET request POST requests are used less frequently than GET requests For POST, you must set the content type: request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); request.send('var1=' + value1 + '&var2=' + value2 ); 20

21 The escape method In the previous slide we constructed our parameter list to the server request.send('var1=' + value1 + '&var2=' + value2 ); This list will be appended to the URL (for a GET ) However, some characters are not legal in a URL For example, spaces should be replaced by %20 The escape method does these replacements for you request.send('var1=' + escape( value1 ) + '&var2=' + escape( value2 )); Look at http://www.w3schools.com/tags/ref_urlencode.asp http://www.w3schools.com/tags/ref_urlencode.asp escape() & unescape() Methods http://www.w3schools.com/jsref/jsref_escape.asp 21

22 Step 4: Get & evaluate the response Ajax uses asynchronous calls—you don’t wait for the response Instead, you have to handle an event request.onreadystatechange = someFunction; This is a function assignment, not a function call Hence, there are no parentheses after the function name When the function is called, it will be called with no parameters function someFunction() { if(request.readyState == 4){ var response = request.responseText; if (http_request.status == 200) { // Do something with the response } } } To be safe, set up the handler before you call the send function 22

23 The readyState property The readyState property defines the current state of the XMLHttpRequest object. Here are the possible values for the readyState property: readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method. readyState=1 after you have called the open() method, but before you have called send(). readyState=2 after you have called send(). r eadyState=3 after the browser has established a communication with the server, but before the server has completed the response. readyState=4 after the request has been completed, and the response data have been completely received from the server. Not all browsers use all states Usually you are only interested in state 4 Mostly from: http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp 23

24 The magic number 4 The callback function you supply is called not just once, but (usually) four times request.readystate tells you why it is being called Here are the states: 0 -- The connection is uninitialized This is the state before you make the request, so your callback function should not actually see this number 1 -- The connection has been initialized 2 -- The request has been sent, and the server is (presumably) working on it 3 -- The client is receiving the data 4 -- The data has been received and is ready for use I don’t know any reason ever to care about the other states I guess the browser just wants you to know it’s not loafing 24

25 The magic number 200 A ready state of 4 tells you that you got a response--it doesn’t tell you whether it was a good response The http_request.status tells you what the server thought of your request 404 Not found is a status we are all familiar with 200 OK is the response we hope to get Look at http://www.w3schools.com/tags/ref_httpmessages.asp 25

26 Putting it all together Head: function getXMLHttpRequest () {... } // from an earlier slide function sendRequest() { getXMLHttpRequest(); var url = some URL request.open("GET", url, true); // or POST request.onreadystatechange = handleTheResponse; request.send(null); // or send( content ), if POST function handleTheResponse() { if (request.readyState == 4) { //4 means I have response if (request.status == 200) { var response = request.responseText; // do something with the response string } else { alert("Error! Request status is " + request.status); } } } Body: 26

27 On the server side The server gets a completely standard HTTP request. Server programming model remains the same It receives standard HTTP GETs/POSTs Can use Servlet, JSP, JSF,... In a servlet, this would go to a doGet or doPost method The response is a completely standard HTTP response, but partial HTML page as a response, the server returns an arbitrary text string (possibly XML, possibly something else). Response content type can be text/xml text/plain text/json text/javascript 27

28 Using response data When you specify the callback function, request.onreadystatechange = someFunction; you can’t specify arguments Two solutions: Your function can use the request object as a global variable This is a very bad idea if you have multiple simultaneous requests You can assign an anonymous function: request.onreadystatechange = function() { someFunction(request); } Here the anonymous function calls your someFunction with the request object as an argument. 28

29 Displaying the response http_request.onreadystatechange = function() { showContentsAsAlert(http_request); }; http_request.open('GET', url, true); http_request.send(null); function showContentsAsAlert(http_request) { if (http_request.readyState == 4) { /* 4 means got the response */ if (http_request.status == 200) { alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } } From: http://developer.mozilla.org/en/docs/AJAX:Getting_Started 29

30 responseText and responseXML The Content-Type in the header tells the type of server response For non-XML, you can use text/html or text/plain For sending XML, it's better to use text/xml When the server sends text/xml, the browser parses it, creates an XML DOM tree, and places this tree in the responseXML object The XML is also available in the responseText object, but to use this you will have to parse it yourself 30

31 Displaying theAjax response Here is the previous code for dealing with a non-XML response: function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.status == 200) { alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } } 31

32 Doing it with XML Here’s an XML file named test.xml : I'm a test. function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.status == 200) { var xmldoc = http_request.responseXML; var root_node = xmldoc.getElementsByTagName('root').item(0); alert(root_node.firstChild.data); } else { alert('There was a problem with the request.'); } } } 32

33 Examples 1- Text Exmple: http://www.w3schools.com/ajax/tryit.asp?filename=t ryajax_first http://www.w3schools.com/ajax/tryit.asp?filename=t ryajax_first 2- XML Exampl http://www.w3schools.com/ajax/tryit.asp?filename=try ajax_responsexml 33

34 HTML DOM vs. XML DOM The DOM for the web page represents HTML The DOM for the XML represents the server's response They have the same methods! 34

35 Problem: Lost response You create a request object, and append your request information to it When the server responds, its result is also in the request object Question: What happens if, before you get a response, you use the request object to send off another request? Answer: You have overwritten the request object, so the response to the original request is lost Solution: In this situation, you will need to create and use more than one request object 35

36 Summary Create an XMLHttpRequest object (call it request) Build a suitable URL, with ? var = value suffix request.open('GET', URL ) request.onreadystatechange = handlerMethod ; request.send(null); function handlerMethod () { if ( request.readyState == 4) { if (http_request.status == 200) { // do stuff } } } 36

37 Sending XML to the server The server is really good at handling name-value pairs If you want to send XML... It pretty much has to be sent as POST XML gets long very quickly All those special characters need to be URL-encoded You have to setRequestHeader("Content-Type", "text/xml") The server doesn't have DOM trees--you will have to parse the XML yourself Bottom line: Sending XML to the server is too much work! 37

38 Problem: Only works the first time You send a request using GET, and it works Something changes on the server, and you want to see the new value, so you send the same request again Nothing happens! Why not? Answer: The browser has cached your URL; it sees that you use it again without change, and gives you the cached response Wrong solution: Turn off browser caching That doesn't work at the level of JavaScript Correct solution: Change the URL in some unimportant way url = url + "?dummy=" + newDate().getTime(); // time is in ms The server is free to ignore this parameter Another correct solution: Use POST instead of GET 38

39 Problem: JavaScript isn’t loaded You put the JavaScript in an external.js file Some browsers ignore the external JavaScript file Solution: Put a space between the opening script tag and the closing script tag Not this: But this: 39

40 XMLHTTP Methods abort()Aborts a request. open(method, uri, [async, [username, [password]]]) Sets properties of request (does not send). (Note about async.) send(content)Sends the request with content in the body. content should be null unless method is ‘post’. 40

41 XMLHTTP Properties onreadystatechangeFunction obj to handle request progress. readyStateRead only. Current request progress. responseTextRead only. Response body as string. responseXMLRead only. Response body parsed as text/xml and in DOM Document obj. statusRead only. HTTP response status code. 41

42 Typical AJAX Flow Make the call Gather information (possibly from HTML form) Set up the URL Open the connection Set a callback method Send the request Handle the response (in callback method) When request.readyState == 4 and request.status == 200 Get the response in either text or xml request.responseText or request.responseXML Process the response appropriately for viewing Get the objects on the page that will change document.getElementById or document.getElementByName, etc. Make the changes 42

43 Instantiating XMLHTTP function getXMLHTTP () { var req = false; if(window.XMLHttpRequest) { try { req = new XMLHttpRequest(); } catch(e) {} } else if(window.ActiveXObject) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } } // end if return req; } // end function 43

44 Instantiating XMLHTTP var request = getXMLHTTP (); request.onreadystatechange = handleReadyStateChange; request.open(‘get’,‘/bar/checkuname.php?u=jessica’); request.send(null); Handling Responses function handleReadyStateChange () { if (!request) return; // ignore unless complete readyState if (request.readyState == 4) { // Ignore unless successful. if (request.status == 200) { // act on the response var xmlbody = request.responseXML; // the line below is important! request = false; processResponse(xmlbody); } } // end function 44

45 Example Response XML Requested username is unavailable, but the script has determined some alternatives. 45

46 Acting on a Response JavaScript’s alert() function? You could use this, but it’s annoying and quite defeats one of the reasons to use AJAX: allowing the application to always remain responsive. A better choice is to manipulate the DOM with JavaScript. 46

47 Manipulating the DOM function processResponse (oXML) { if (!oXML) return; if (!oXML.documentElement) return; var doc = oXML.documentElement; // return a nodeList of all username elements var unames = doc.getElementsByTagName('username'); var msgs = new Array(); // iterate through the username nodeList for (var i=0; i<unames.length; i++) { var u = unames.item(i); var username = u.getAttribute('value'); var availability = u.getAttribute('available'); // make the available attribute more user-friendly if (availability == 'true') { availability = 'available'; } else { availability = 'not available'; } msgs[msgs.length] = 'Username '+ username +' is '+ availability; } 47

48 processResponse Cont’d // create an unordered list element ul = document.createElement('ul'); ul.id = 'msg'; // for each message, create a list item // element and a text node containing // the message. The text node is a child // node of the list item element, and the // the list item is a child node of the // unordered list element. for (var k=0; k<msgs.length; k++) { var li = document.createElement('li'); var txt = document.createTextNode(msgs[k]); li.appendChild(txt); ul.appendChild(li); } // obtain a reference to the maindiv element // and insert our new unordered list just before it var maindiv = document.getElementById('maindiv'); maindiv.parentNode.insertBefore(ul,maindiv); } 48

49 Altered DOM After Manipulation … parentNode ul li Username jessica is not available Username jess is available Username jessica2005 is available Username jessie is available maindiv … 49

50 AJAX Libraries SAJAX Makes things marginally easier Doesn’t support XML responses uses innerHTML, so can’t even use DOM CPAINT Supports XML and text responses Actively developed and mature Documentation a little immature JPSPAN Excellent abstraction Seamlessly “imports” server-side objects into JavaScript Clear documentation Doesn’t support Opera Limited usefulness 50

51 Further Information http://developer.apple.com/internet/webcontent/xmlhttpreq.html http://xulplanet.com/references/objref/XMLHttpRequest.html http://www.mozilla.org/xmlextras/ http://www.ajaxpatterns.org/ http://www.ajaxmatters.com/ JavaScript and HTML DOM Reference http://www.w3schools.com/jsref/ http://www.w3schools.com/jsref/dom_obj_document.asp http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_for m_elements http://www.w3schools.com/jsref/dom_obj_document.asp 51

52 Another Example 52

53 53

54 54

55 55


Download ppt "Ajax Dr. Reda Salama. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better,"

Similar presentations


Ads by Google