Presentation is loading. Please wait.

Presentation is loading. Please wait.

AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.

Similar presentations


Presentation on theme: "AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library."— Presentation transcript:

1 AJAX

2 Objectives Understand and apply AJAX Using AJAX in DOJO library

3 Course Timetable Duration: 180 minutes Break: 15 minutes

4 Prerequisites HTML/DHTML JavaScript CSS XML Web Programming Basics

5 Agenda When we choose AJAX? What is AJAX? Why we choose AJAX? How to apply AJAX? Sample AJAX in DOJO Exercise

6 When we choose Ajax? - Auto Completion Google - http://www.google.com.vn/

7 When we choose Ajax? – Real-time validation

8 When we choose Ajax? – Refreshing partial data

9 What is Ajax? AJAX = Asynchronous JavaScript and XML Ajax is not new programming language, but a new way to use existing standards. Using JavaScript object XmlHttpRequest to communicate asynchronously with a server-side component

10

11 Components: Traditional Web vs. AJAX

12 User Interface: Traditional Web & AJAX

13 Why we choose Ajax? Pros –Creating better, faster, and more interactive web applications –JavaScript can communicate directly with the server without reloading the page –Web pages request small bits of information from the server instead of whole pages Cons –Breaks back button functionality –Javascript can be turned off in browser

14 How to apply Ajax? – Steps Creating an instance Sending a Request to the Server Handle return results

15 XMLHttpRequest - Creating an instance function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } return this.req; }

16 XMLHttpRequest – Sending a request to server xmlHttp.open(method, url); –Method: The most commonly used methods are GET and POST –URL: This parameter identifies the page being requested xmlHttp.send(params); –The send method takes one parameter, which is used for POST data. When the request is a simple GET that doesn’t pass any data to the server, like our current request, we set this parameter to null.

17 Sending a Request to the Server with GET var url = "sample.jsp"; var params = "param1=1&param2=2"; xmlRequest.open("GET", url + " ? " + params); xmlRequest.send(null);

18 Sending a Request to the Server with POST var url = "sample.jsp"; var params = "param1=1&param2=2"; xmlRequest.open("POST", url); // Send the proper header information along with the request xmlRequest.setRequestHeader("Content-type", "application/x-www-form- urlencoded"); xmlRequest.send(params);

19 XMLHttpRequest - Handle return results responseText (html format “text/html”) responseXml (xml format “text/xml”) xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response if (xmlRequest.getResponseHeader("Content-type").indexOf("text/xml") >= 0) { alert(xmlRequest.responseXML); } else { alert(xmlRequest.responseText); }

20 XMLHttpRequest - readyState readyStateDescription 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is complete

21 XMLHttpRequest - status code statusstatusText 200 OK 404Not Found 500 Internal Server error …

22 Example var url = "sample.jsp"; var params = "param1=1&param2=2";

23 Example – Client (Text format) AJAX Hello World function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } return this.req; } // When the user clicking on the Hello World !!! button function hello() { // Create XMLHttpRequest instance var xmlRequest = getXMLHttpRequest(); // Send the request to the server using GET method var url = "sample.jsp"; var params = "param1=1&param2=2"; xmlRequest.open("GET", url + "?" + params); xmlRequest.send(null); // Register the event to process data xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response alert(xmlRequest.responseText); } Hello World

24 Example – Server (Text format) The file “sample.jsp” AJAX Training

25 Example – Client (XML format) AJAX Hello World function getXMLHttpRequest() { if (!this.req) { try { // Try to create object for Firefox, Safari, IE7, etc. this.req = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } return this.req; } // When the user clicking on the Hello World !!! button function hello() { // Create XMLHttpRequest instance var xmlRequest = getXMLHttpRequest(); // Send the request to the server using GET method var url = "sampleXML.jsp"; var params = "param1=1&param2=2"; xmlRequest.open("GET", url + "?" + params); xmlRequest.send(null); // Register the event to process data xmlRequest.onreadystatechange = function() { if (xmlRequest.readyState == 4 && xmlRequest.status == 200) { // Get data from the server's response var xml = xmlRequest.responseXML; var title = xml.getElementsByTagName("title").item(0).firstChild.nodeValue; alert(title); } Hello World

26 Example – Server (XML format) The file “sampleXML.jsp” <% response.setContentType("text/xml"); PrintWriter output = response.getWriter(); try { output.write(" "); output.write("AJAX Training " + request.getParameter("param1") + " " + request.getParameter("param2")); output.write(" "); output.close(); } catch (Exception e) { e.printStackTrace(); } %>

27 Exercise Using POST method Replace the “Hello World” text by exactly the text retrieved from the server The server returns the html format with the given color parameter to display the text “AJAX Training ”

28 AJAX in DOJO DOJO –Introduction –Directory Structure –Basic Template –Logging & Debugging –Dom & Event AJAX –Http Get –Http Post –Submit Form –Get Json Object –XHR Arguments

29 DOJO - Introduction DOJO is an Open Source DHTML toolkit written in JavaScript. DOJO supplies a solid set of tools for DOM manipulation, Animations, Ajax, Event and keyboard normalization, Internationalization (i18n) and Accessibility (a11y) … Main site: http://dojotoolkit.org/

30 DOJO – Directory Structure

31 DOJO - Basic Template Dojo Toolkit Test Page <script type="text/javascript" src="js/dojo/dojo.js" djConfig="parseOnLoad:true, isDebug:true"> /* our JavaScript will go here */ /* our CSS can go here */

32 DOJO - Logging & Debugging console.log("Nothing happening"); console.debug("Checking to make sure nothing happened"); console.info("Something might happen."); console.warn("Something happened, but it's no big deal."); console.error("Cough cough!");

33 DOJO - DOM & Event DOM Ready dojo.addOnLoad dojo.addOnLoad (function() { console.log("The document is ready"); }); Selecting DOM Nodes with dojo.query & dojo.byId // Query by tag. Equivalent to document.getElementsByTagName("img"); console.dir(dojo.query("img")); // Query by class. console.dir(dojo.query(".offToSeeTheWij")); // Query by id. Equivalent to document.getElementById("widget123"); console.dir(dojo.query("#widget123")); console.dir(dojo.byId("widget123")); // Select just image tags with the class offToSeeTheWij console.dir(dojo.query("img.offToSeeTheWij"));

34 DOJO - DOM & Event … Chain of Effects dojo.query("#heading") // add "testClass" to its class="" attribute.addClass("testClass") // set background color.style("backgroundColor","gray"); Event Handlers dojo.query(".deadLink").onclick(function(evt) { console.log('Clicking'); }); dojo.connect(dojo.byId("mainForm"), "onsubmit", formSubmit);

35 AJAX - Http Get dojo.xhrGet({ url: "sample.jsp?param1=1&param2=2", handleAs: "text", load: function(data,args) { dojo.byId("heading").innerHTML = data; }, // if any error occurs, it goes here: error: function(error,args) { console.warn("error!",error); } });

36 AJAX - Http Post dojo.xhrPost({ url:"sample.jsp", content: { "param1":"1", "param2":2 }, load: function(data,ioargs){ dojo.byId("heading").innerHTML = data; } });

37 AJAX - Submit Form var formSubmit = function(e) { e.preventDefault(); // prevent the form from actually submitting dojo.xhrPost({// submit the form in the background url: "sample.jsp", form: "mainForm", handleAs: "text", load: function (data, ioargs) { dojo.byId("heading").innerHTML = data; } }); }; dojo.addOnLoad(function() { var theForm = dojo.byId("mainForm"); dojo.connect(theForm,"onsubmit",formSubmit); });

38 AJAX - Get JSON (JavaScript Object Notation) object { foo: "bar", name: "SitePen", aFunction: function() { alert("internal function run"); }, nested: { sub: "element", another: "subelement" }

39 AJAX - Get JSON object … var postData = function(){ dojo.xhrPost({ url: "sample.json", handleAs: "json", load: function (data,ioargs){ // success: set heading, run function dojo.byId("heading").innerHTML += " by: "+data.name; if (data.aFunction && data.aFunction()) { // we just ran data.aFunction(). should alert()... } }); }; dojo.addOnLoad(postData);

40 Ajax – XHR Arguments dojo.xhrGet(args: dojo.__xhrArgs); dojo.xhrPost(args: dojo._xhrArgs);dojo.__xhrArgs contentObject Optional. Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request. errorFunction Optional. formDOMNode Optional. DOM node for a form. Used to extract the form values and send to the server. handleFunction Optional. handleAsString Optional. Acceptable values are: text (default), json, json-comment- optional, json-comment-filtered, javascript, xml. headersObject Optional. Additional HTTP headers to send in the request. loadFunction Optional. preventCacheBoolean Optional. Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests. syncBoolean Optional. false is default. Indicates whether the request should be a synchronous (blocking) request. timeoutInteger Optional. Milliseconds to wait for the response. If this time passes, the then error callbacks are called. urlString URL to server endpoint.

41 Demo & Exercise

42 Questions & Answers

43 Thanks for Your Attention


Download ppt "AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library."

Similar presentations


Ads by Google