ajax
play

Ajax Asynchronous JavaScript and XML Combination of JavaScript, - PowerPoint PPT Presentation

Ajax Asynchronous JavaScript and XML Combination of JavaScript, CSS, XHTML, XML, and the XMLHttpRequest object to dynamically modify a portion of a web page using data from the server Goal is to make web applications look and


  1. Simple Example ● XHTML <form action=""> <p> <input type="button" value="Fetch message 1" onclick = "getData(' ajaxphp2.php?data=1 ', 'targetDiv')" /> <input type="button" value="Fetch message 2" onclick = "getData(' ajaxphp2.php?data=2 ', 'targetDiv')" /> </p> </form> <div id="targetDiv"> <p>Fetched message will appear here.</p> </div> http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxphp2.html Slide Set 5 24

  2. Simple Example ● PHP code <?php extract($_GET); if ($data == "1") echo 'Welcome to Ajax!'; if ($data == "2") echo 'Ajax is fun!'; ?> Slide Set 5 25

  3. Passing data to PHP script using POST ● Using a post request, the data is encoded in the body of the message ● Modifying the simple example to use a post: – change the PHP code so that it accesses POST array instead of GET array – change the XMLHttpRequest object open to do a POST instead of a GET – call the setRequestHeader method of the XMLHttpRequest object – send the data to the server using the XMLHttpRequest object send method Slide Set 5 26

  4. The JavaScript var XMLHttpRequestObject = false; if (window.XMLHttpRequest) //Firefox way to create object XMLHttpRequestObject = new XMLHttpRequest(); else if (window.ActiveXObject) //IE way to create object XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); else alert("Ajax not supported"); function getData(dataSource, divID, data ) { var obj = document.getElementById(divID); obj = obj.getElementsByTagName("p")[0]; if (XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) obj.innerHTML = XMLHttpRequestObject.responseText; } XMLHttpRequestObject.send("data=" + data); } else obj.innerHTML = "Ajax not supported"; } Slide Set 5 27

  5. The XHTML <body> <form action=""> <p> <input type="button" value="Fetch message 1" onclick = "getData('ajaxphp3.php', 'targetDiv', 1 )" /> <input type="button" value="Fetch message 2" onclick = "getData('ajaxphp3.php', 'targetDiv', 2 )" /> </p> </form> <div id="targetDiv"> <p>Fetched message will appear here.</p> </div> </body> Slide Set 5 28

  6. The PHP script <?php extract($_POST); if ($data == "1") echo 'Welcome to Ajax!'; if ($data == "2") echo 'Ajax is fun!'; ?> Example at: http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxphp3.html Slide Set 5 29

  7. Using Ajax with XML ● Need to call overrideMimeType method to force browser to treat data received from server to be XML XMLHttpRequestObject.overrideMimeType(“text/xml”); ● Callback function will access the responseXml property of the XMLHttpRequest object (instead of responseText property) xmlDocument = XMLHttpRequestObject.responseXML; ● Can use the DOM 1 implementation to access the XML Slide Set 5 30

  8. Ajax with XML example 1 ● Example builds a drop-down list from XML obtained from the server ● GET is sent to the server to retrieve the appropriate XML file http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxxml1.html Slide Set 5 31

  9. The XML files <?xml version = "1.0" ?> <?xml version = "1.0" ?> <cities> <cities> <city>Asheville</city> <city>Annapolis</city> <city>Boone</city> <city>Bethesda</city> <city>Charlotte</city> <city>Gaithersburg</city> <city>Raleigh</city> <city>Waldorf</city> <city>Wilmington</city> </cities> </cities> maryland.xml northcarolina.xml Slide Set 5 32

  10. The JavaScript code, part 1 window.onload = initialize; function initialize() { getXMLHttpRequest(); //reset form to the selected item var obj = document.getElementById("myform"); obj.reset(); obj = document.getElementById("states"); obj.onchange = getSelect; } function getSelect() { var obj = document.getElementById("states"); if (obj.value == "Maryland") getData("maryland.xml"); else if (obj.value == "North Carolina") getData("northcarolina.xml"); } Slide Set 5 33

  11. The JavaScript code, part 2 var XMLHttpRequestObject = false; function getXMLHttpRequest() { if (window.XMLHttpRequest) //Firefox way to create object XMLHttpRequestObject = new XMLHttpRequest(); else { try { XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Ajax not supported"); } } } } Slide Set 5 34

  12. The JavaScript code, part 3 function getData(dataSource) { if (XMLHttpRequestObject) { XMLHttpRequestObject.open("GET", dataSource); //need this to make Firefox treat the returned data //as xml XMLHttpRequestObject.overrideMimeType("text/xml"); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { buildSelect(XMLHttpRequestObject.responseXML) ; } } XMLHttpRequestObject.send(null); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; } Slide Set 5 35

  13. The JavaScript code, part 4 function buildSelect(xml) { //get array of city nodes from XML var cities = xml.getElementsByTagName("city"); //get select element from HTML document var select = document.getElementById("cities"); for (var i = 0; i < cities.length; i++) { //first child of the cities node is a text node select.options[i] = new Option(cities[i].firstChild.data); } } Slide Set 5 36

  14. The HTML <body> <form id="myform" action=""> <p> <select size="1" id="states"> <option value="">Select a State</option> <option value="Maryland">Maryland</option> <option value="North Carolina">North Carolina</option> </select> </p> <p> <select size="1" id="cities"> </select> </p> </form> <div id ="errmsg"> </div> </body> Slide Set 5 37

  15. Ajax with XML, example 2 ● This example sends the name of the state to a PHP script on the server ● Data sent to the server via a POST ● PHP script opens a file containing state names and cities; reads through the file until the matching state name is found and dynamically builds the XML http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxxml2.html Slide Set 5 38

  16. The states.txt file North Carolina: Asheville Boone Charlotte Raleigh Wilmington Maryland: Annapolis Bethesda Gaithersburg Waldorf Slide Set 5 39

  17. The PHP code, part 1 <?php extract($_POST); echo '<?xml version="1.0" ?><cities>'; getData($data); echo '</cities>'; Slide Set 5 40

  18. The PHP code, part 2 function getData($state) { $file = fopen("states.txt", "r") or exit("Unable to open file"); $done = false; //remove backslashes (magic quotes) and quotes $state = stripslashes($state); $state = str_replace("'", "", $state); $state = str_replace('"', "", $state); $state = $state.":\n"; while ($done == false && !feof($file)) { $line = fgets($file); if (strcmp($line, $state) == 0) { $line = fgets($file); do { echo '<city>'.$line.'</city>'; $line = fgets($file); } while (!feof($file) && strpos($line, ':') === false); $done = true; } } } ?> Slide Set 5 41

  19. Some of the JavaScript, part 1 function getSelect() { var obj = document.getElementById("states"); if (obj.value == "Maryland") getData("ajaxxml2.php", "Maryland"); else if (obj.value == "North Carolina") getData("ajaxxml2.php", "North Carolina"); } Slide Set 5 42

  20. Some of the JavaScript, part 2 function getData(dataSource, data) { if (XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //post header required //need this to make Firefox treat the file as an xml file XMLHttpRequestObject.overrideMimeType("text/xml"); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { buildSelect(XMLHttpRequestObject.responseXML) ; } } XMLHttpRequestObject.send("data="+data); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; } Slide Set 5 43

  21. Handling multiple concurrent XMLHttpRequests ● What would happen if the user clicks on buttons that start up simultaneous XMLHttpRequests? – in earlier examples, only one XMLHttpRequest object is available – this one object would be modified by both requests and we wouldn't know which request is being satisfied ● Solution: – multiple XMLHttpRequest objects Slide Set 5 44

  22. Multiple XMLHttpRequest objects ● One solution is to store XMLHttpRequest objects in an array ● Easier and better solution is to use inner functions – every time an outer function is called, a new copy of that function (and its local variables) is created – inner functions have access to outer function local variables Slide Set 5 45

  23. Multiple XMLHttpRequest objects function getData(dataSource, data) { //create new XMLHttpRequest object var XMLHttpRequestObject = getXMLHttpRequest(); if (XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //need this to make Firefox treat the file as an xml file XMLHttpRequestObject.overrideMimeType("text/xml"); XMLHttpRequestObject.onreadystatechange = function() { if ( XMLHttpRequestObject. readyState == 4 && XMLHttpRequestObject .status == 200) { buildSelect( XMLHttpRequestObject .responseXML); } } XMLHttpRequestObject.send("data="+data); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; } http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxxml3.html Slide Set 5 46

  24. Handling JavaScript sent by the server ● Don't really want the server side code to know the details of the client side code or vice-versa ● But some server-side APIs (such as Google suggest) return JavaScript ● For these, you'll have to be able to download and execute the JavaScript ● The JavaScript may be – function call – or, JavaScript object Slide Set 5 47

  25. window.onload = initialize; JavaScript sent by the function initialize() { //reset form to the selected item server, Example 1 var obj = document.getElementById("mydiv"); obj.onclick = getData ; } function getData() { //create new XMLHttpRequest object var XMLHttpRequestObject = getXMLHttpRequest(); if (XMLHttpRequestObject) { XMLHttpRequestObject.open("GET", "ajaxjs1.php"); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { //eval evaluates the text as JavaScript code eval(XMLHttpRequestObject.responseText) ; } } XMLHttpRequestObject.send(null); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; } Slide Set 5 48

  26. JavaScript sent by the server, Example 1 function greeting() { var obj = document.getElementById("mydiv"); obj.innerHTML = "<h2>Hello CS 5530 Students</h2>" } <?php echo "greeting();" ?> http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxjs1.html Slide Set 5 49

  27. JavaScript sent by server, Example 2 Use PHP to create a string representing a JavaScript object <?php $text = "{function: 'greeting', operand: 'CS 5530'};"; echo $text; ?> Use eval to create the JavaScript object var object; eval('object = ' + XMLHttpRequestObject.responseText) ; Use eval to invoke the method specified by the object with its parameter(s) eval(object.function + '("' + object.operand + '");'); http://www.cs.appstate.edu/~can/classes/5530/set5/ajaxjs2.html Slide Set 5 50

  28. Calling another domain in Ajax ● Browser will display a warning if an Ajax script tries to access a Web domain the script didn't come from ● Solution is to use a server-side script to access the domain and use Ajax to access the server- side script Slide Set 5 51

  29. Connecting to Google Suggest ● Can't connect to Google Suggest directly from our web page, but we can use a PHP script to connect to it ● Google Suggest returns a JavaScript function call; one of the parameters is an Array of results Slide Set 5 52

  30. PHP script for connecting to Google Suggest <?php $data = urlencode($_GET["qu"]); $file = fopen("http://www.google.com/complete/search?h1=en&js=true&qu=". $data, "r"); while (!feof($file)) { $line = fgets($file); echo $line; } ?> Notice that the qu parameter for google suggest comes from my web document. URLs in PHP are opened and read from just like files. http://www.cs.appstate.edu/~can/classes/5530/set5/google.php Slide Set 5 53

  31. What Google Suggest returns ● If my PHP script is invoked like this: http://www.cs.appstate.edu/~can/classes/5530/set5/google.php?qu='Mary' ● what is echoed by the script is: window.google.ac.Suggest_apply(frameElement, "\\\x27Mary\\\x27", new Array(2, "mary kay", "3,460,000 results", "mary poppins", "2,560,000 results", "mary louise parker", "2,160,000 results", "mary j blige", "2,880,000 results", "mary elizabeth winstead", "589,000 results", "mary kate olsen", "2,570,000 results", "mary kate and ashley", "3,020,000 results", "mary winkler", "1,780,000 results", "mary kay cosmetics", "1,140,000 results", "mary queen of scots", "1,470,000 results"), new Array("")); ● Notice that the third parameter contains an array of the search results Slide Set 5 54

  32. Eliminating Browser Caching ● Browser caching – Browser has already visited URL once and stored response from the visit (cached it) – Rather than visiting the PHP script again, browser returns result of last visit – Of course, this is bad if you are the developer and you're actively modifying the script ● Solution to this problem is to pad with the date the url so that it is unique every time Slide Set 5 55

  33. Eliminating Browser Caching ● Date parameter added to the URL isn't used; it is only there to cause browser to connect to server each time XMLHttpRequestObject.open("GET", “script.php?d=' + new Date().getTime()); Slide Set 5 56

  34. Client-side Ajax Frameworks ● Many free JavaScript code libraries are available for downloading ● Some provide support just for Ajax ● Others provide entire application solutions ● Majax (Minimalist Ajax) Framework http://sourceforge.net/projects/unips ● Sack Framework http://twilightuniverse.com/projects/sack Slide Set 5 57

  35. Client-side Frameworks ● XHConn Framework http://xkr.us/code/javascript/XHConn ● uniAjax Framework http://uniajax.net ● AjaxGear Framework http://www.ajaxgear.com ● AjaxRequest Framework http://www.ajaxtoolbox.com Slide Set 5 58

  36. Client-side Frameworks ● Http Framework (provides functionality to force or prevent caching) http://adamv.com/dev/javascript/http_request ● Interactive Website Framework (specializes in handling XML) http://sourceforge.net/projects/iwf ● Dojo http://dojotoolkit.org Slide Set 5 59

  37. Majax ● Small JavaScript library that provides two functions – majax_get – majax_post ● Both of these run asynchronously and plain text (no XML) is returned in the variable into the variable MAJAX_RESPONSE ● The callback function is registered using MAXCM_COMPLETE.register(callback) Slide Set 5 60

  38. Majax get example <script type="text/javascript" src="majax-0.1.1/majax.js"></script> <script type="text/javascript" > //<![CDATA[ function getData(dataSource) { //pass the url to majax get majax_get(dataSource, null); } function handler() { var div=document.getElementById("targetDiv"); div.innerHTML = MAJAX_RESPONSE; } //register the XMLHttpRequest done handler MAJAXCM_COMPLETE.register(handler); //]]> </script> </head> <body> <form action=""> <p><input type="button" value="Fetch the message" onclick = "getData('msg.txt')" /></p> </form> <div id="targetDiv"> <p>Fetched message will appear here.</p> </div> 61 http://www.cs.appstate.edu/~can/classes/5530/set5/majaxgetmsg1.html

  39. Majax post example <script type="text/javascript" src="majax-0.1.1/majax.js"></script> <script type="text/javascript" > //<![CDATA[ function getData(dataSource, data) { //pass the url to majax get majax_post(dataSource, "str="+data); } function handler() { var div=document.getElementById("targetDiv"); div.innerHTML = MAJAX_RESPONSE; } //register the XMLHttpRequest done handler MAJAXCM_COMPLETE.register(handler); //]]> </script> </head> <body> <form action=""> <p> <input type="button" value="Fetch the message" onclick = "getData('majaxgetmsg2.php', 'CS 5530')" /></p> </form> <div id="targetDiv"><p>Fetched message will appear here.</p></div> http://www.cs.appstate.edu/~can/classes/5530/set5/majaxgetmsg2.html 62

  40. Dojo ● Open source DHTML toolkit written in JavaScript ● Three major layers – Dojo core – Dijit – widget system – DojoX – incubator area for Dojo (works in progress) ● Dojo also provides supports for Ajax Slide Set 5 63

  41. Dojo XHR ● Dojo XHR routines expect JSON (JavaScript Object Notation) as input ● The JSON indicates – URL – callback function – error function – what type of response to receive from server (XML, text, JavaScript, JSON) – form for posted data Slide Set 5 64

  42. JSON { url: "file.txt", handleAs: "text", timeout: 5000, load: function(response, ioArgs) { dojo.byId("cargo").innerHTML = response; return response; }, error: function(response, ioArgs) { console.error("HTTP status code: ", ioArgs.xhr.status); return response; } } Slide Set 5 65

  43. Dojo Example <script type="text/javascript" src="http://o.aolcdn.com/dojo/0.9.0/dojo/dojo.xd.js"></script> <script type="text/javascript"> //<![CDATA[ function hello() { dojo.xhrGet( { //The following URL must match that used to test the server. url: "http://www.cs.appstate.edu/~can/classes/5530/set5/msg.txt", handleAs: "text", timeout: 5000, // Time in milliseconds // The LOAD function will be called on a successful response. load: function(response, ioArgs) { dojo.byId("cargo").innerHTML = response; return response; }, error: function(response, ioArgs) { console.error("HTTP status code: ", ioArgs.xhr.status); return response; } }); } Slide Set 5 66 //]]> </script>

  44. Dojo Example <script type="text/javascript"> //<![CDATA[ dojo.addOnLoad(hello); //]]> </script> </head> <body> <div id="cargo" style="font-size: big"></div> <!--.--> </body> </html> http://www.cs.appstate.edu/~can/classes/5530/set5/dojohello1.html Welcome to Ajax! http://www.cs.appstate.edu/~can/classes/5530/set5/msg.txt Slide Set 5 67

  45. Sending data to server ● When using xhrGet, you can append data to the URL: url: "http://www.cs.appstate.edu/~can/classes/5530/set5/dojohello2.php?str='CS 5530'", ● However, this only supports static data; dynamic data must be sent using xhrPost by specifying the id of the form holding the data Slide Set 5 68

  46. Server-Side Ajax Frameworks ● These help with both server-side programming and client-side programming ● Framework can generate the JavaScript needed by the browser ● Frameworks are available in many different languages including PHP, Java, Ruby, Python, Perl and more Slide Set 5 69

  47. Server-Side Ajax Frameworks ● Sajax http://www.modernmethod.com/sajax ● Xajax http://xajax.sf.net ● LibAjax http://sourceforge.net/projects/libajax ● Direct Web Remoting and Java http://getahead.ltd.uk/dwr Slide Set 5 70

  48. Server-Side Ajax Frameworks ● Ajax Tag Library and Java (relies on JSP custom tags) http://ajaxtags.sourceforge.net ● Swato and Java https://swato.dev.java.net/ ● Ruby on Rails http://rubyonrails.com/down Slide Set 5 71

  49. Sajax ● Creates JavaScript on the server that is needed by the browser so all you need is server-side code ● Can be written in many different languages including ASP, ColdFusion, Lua, Perl, Python, Ruby, Io ● When the browser requests a PHP (or other) script stored on the server, the script is executed and the JavaScript generated is sent to the browser Slide Set 5 72

  50. Sajax ● Sajax provides functionality to connect the server-side code to the JavaScript coded ● Important Sajax functions – sajax_init(); //sets up Sajax – sajax_export(“function”); //makes a server-side function available to JavaScript function – sajax_handle_client_request(); //connects server- side and client-side code – sajax_show_javascript(); //generates the JavaScript Slide Set 5 73

  51. Sajax Example PHP code at top of file <? require("sajax-0.12/php/Sajax.php"); // The server code that does the work. function adder($operand1, $operand2) { return $operand1 + $operand2; } sajax_init(); sajax_export("adder"); sajax_handle_client_request(); ?> Slide Set 5 74

  52. PHP code followed by web document sent to client <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sajax Example</title> <script type="text/javascript"> //<![CDATA[ <? sajax_show_javascript(); ?> function do_adder() { var operand1, operand2; operand1 = document.getElementById("operand1").value; operand2 = document.getElementById("operand2").value; x_adder(operand1, operand2, show_results); } function show_results (result) { document.getElementById("result").value = result; } //]]> </script> </head> Slide Set 5 75

  53. Here's the rest of the document <body> <h1>Sajax Example</h1> <p> <input type="text" name="operand1" id="operand1" value="4" size="3" /> + <input type="text" name="operand2" id="operand2" value="5" size="3" /> = <input type="text" name="result" id="result" value="" size="3" /> <input type="button" name="check" value="Add" onclick="do_adder(); return false; /> </p> </body> </html> http://www.cs.appstate.edu/~can/classes/5530/set5/sajax1.php Slide Set 5 76

  54. Sajax Example ● The call to x_adder causes a call to be made to adder in the PHP script ● Body of x_adder function x_adder() { sajax_do_call("adder", x_adder.arguments); } ● x_adder.arguments is the array of arguments passed to x_adder; last argument is the name of the JavaScript function to be executed when server responds ● sajax_do_call does the Ajax work Slide Set 5 77

  55. Ajax Example ● Downloading an image from the server ● Image name is retrieved from the server using Ajax and then an <img> element is built using the image name ● This is useful when the application developer doesn't know the name of the images on the server; for example, if the images initially come from the client Slide Set 5 78

  56. The JavaScript window.onload = initialize; function initialize() { var obj = document.getElementById("Dog"); obj.onclick = getImage; var obj = document.getElementById("Cat"); obj.onclick = getImage; } function getImage() { var obj = document.getElementById("Dog"); if (obj == this) getData("downloadimage.php", "Dog"); var obj = document.getElementById("Cat"); if (obj == this) getData("downloadimage.php", "Cat"); } Slide Set 5 79

  57. The JavaScript function getXMLHttpRequest() { if (window.XMLHttpRequest) //Firefox way to create object return new XMLHttpRequest(); else { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Ajax not supported"); return null; } } } } Slide Set 5 80

  58. The JavaScript function getData(dataSource, data) { //create new XMLHttpRequest object var XMLHttpRequestObject = getXMLHttpRequest(); if (XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { displayImage(XMLHttpRequestObject.responseText); } } XMLHttpRequestObject.send("data="+data); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; } function displayImage(imageName) { obj = document.getElementById("imageLoc"); obj.innerHTML = '<img src="' + imageName + '" alt="A Pic" />'; } Slide Set 5 81

  59. The HTML <body> <form id="myform" action=""> <p> <input type="button" id="Dog" value="Show Dog Image" /> <input type="button" id="Cat" value="Show Cat Image" /> </p> </form> <div id ="imageLoc"> </div> </body> http://www.cs.appstate.edu/~can/classes/5530/set5/downloadimage.html Slide Set 5 82

  60. The PHP <?php extract($_POST); getData($data); function getData($image) { //remove backslashes (magic quotes) and quotes $image = stripslashes($image); $image = str_replace("'", "", $image); $image = str_replace('"', "", $image); if (strcmp($image, "Dog") == 0) echo "dog.jpg"; else if (strcmp($image, "Cat") == 0) echo "cat.jpg"; else echo $image." not found"; } ?> Slide Set 5 83

  61. Ajax Timeout ● What should you do if the server doesn't respond? ● Display an alert or error message so that the user can retry or give up ● Don't want user to be left in the dark, wondering what is happening Slide Set 5 84

  62. Ajax Timeout ● Timeout function – create one that will be executed after some period of time executes; will display an alert message if server hasn't responded ● Two variables – timeoutSet – initially false; set to true if a timeout function has been set (keeps timeout being set again) – downloadOK – initially false; set to true if successful download occurs (prevents timeout function from displaying alert message) Slide Set 5 85

  63. Ajax Timeout function getImage() { var obj = document.getElementById("Dog"); //deliberately mis-name php script to see my timeout alert if (obj == this) getData("downloadimag.php", "Dog"); var obj = document.getElementById("Cat"); if (obj == this) getData("downloadimage.php", "Cat"); } http://www.cs.appstate.edu/~can/classes/5530/set5/timeout.html Slide Set 5 86

  64. function getData(dataSource, data) { var XMLHttpRequestObject = getXMLHttpRequest(); if (XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); var timeoutSet = false; var downloadOK = false; XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 1 && timeoutSet == false) { window.setTimeout( function() { if (!downloadOK) { alert("Sorry, time out."); XMLHttpRequestObject.abort(); } }, 1000); //call function literal in 1000 milliseconds timeoutSet = true; } if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { downloadOK = true; displayImage(XMLHttpRequestObject.responseText); } } XMLHttpRequestObject.send("data="+data); } else document.getElementById("errmsg").innerHTML = "Ajax not supported"; 87 }

  65. XML and Ajax ● XML is a text based way of storing data which is why it is so popular for the internet ● Two versions available, 1.0 and 1.1 (1.1 supports a larger character set) ● Two primary correctness criteria – well-formedness – legal tags and nesting – validity – ● what the tags are; which tags must be nested within other tags ● specified by a DTD or an XML schema Slide Set 5 88

  66. JavaScript built-in properties (review) ● attributes ● nextSibling ● childNodes ● nodeName ● documentElement ● nodeType (root element) ● nodeValue ● firstChild ● previousSibling ● lastChild ● localName (without namespace) Slide Set 5 89

  67. nodeType property values ● 1 – Element ● 8 – XML comment ● 2 – Attribute ● 9 – XML document node ● 3 – Text node ● 10 – XML DTD ● 4 – CDATA ● 11 – XML document ● 5 – XML entity fragment reference ● 12 – XML Notation ● 6 – XML entity node ● 7 – XML processing instruction Slide Set 5 90

  68. XML Example <?xml version="1.0"?> <!DOCTYPE name [ <!ELEMENT name (first, last) > <!ELEMENT first (#PCDATA) > <!ELEMENT last (#PCDATA) > <!ENTITY mr "Mister"> ]> <name> <first>&mr; Jack</first> <last>Sprat</last> </name> http://www.cs.appstate.edu/~can/classes/5530/set5/name.xml Slide Set 5 91

  69. JavaScript to traverse the XML handleXML( XMLHttpRequestObject.responseXML ); function handleXML( xml ) { var XMLstr = new stringTree(); XMLstr.traverse(0, xml); var obj = document.getElementById("mydiv1"); displayData(obj, "<h2>XML document</h2>" + XMLstr.str); } Slide Set 5 92

  70. JavaScript to traverse XML function stringTree() { this.str = ""; this.traverse = function traverse(level, node) { this.str = this.str + "Level: " + level + ", Node Name: " + node.nodeName + ", Node Type: " + node.nodeType + ", Node Value: " + node.nodeValue; if (node.hasChildNodes()) { this.str = this.str + " { "; Of course, this is var children = node.childNodes; just like our JavaScript for (var i = 0; i < children.length; i++) to traverse an XHTML this.str = this.str + children[i].nodeName + " "; document. this.str = this.str + " }\n"; //visit the next level for (var i = 0; i < children.length; i++) this.traverse(level + 1, children[i]) } else this.str = this.str + "\n"; } } 93 http://www.cs.appstate.edu/~can/classes/5530/set5/name.html

  71. Differences in Document Tree ● If you view the URL indicated on the previous slide in IE and Firefox, you'll notice they generate very different document trees ● Major difference is due to whitespace outside of the elements – Firefox creates nodes for this whitespace; IE does not 94

  72. JavaScript to remove whitespace function removeWhiteSpace(xml) { var i; for (i = 0; i < xml.childNodes.length; i++) { var currentNode = xml.childNodes[i]; if (currentNode.nodeType == 1) { //element node removeWhiteSpace(currentNode); } if (((/^\s+$/.test(currentNode.nodeValue))) && (currentNode.nodeType == 3)) { //empty text node xml.removeChild(xml.childNodes[i--]); } } } http://www.cs.appstate.edu/~can/classes/5530/set5/name2.html Slide Set 5 95

  73. Retrieving attributes ● XML <member role=”chair”>Sally Worker</member> ● Would like to retrieve the value of the role attribute ● Assuming obj points to the member node: attributes = obj.attributes; // attributes of this member node value = attributes.getNamedItem(“role”); // role attribute value Slide Set 5 96

  74. <?xml version="1.0"?> <events> <event type="Food"> <event_title>Cookie Dough Fundraiser</event_title> <committee> <member role="chair">Jane Doe</member> <member role="secretary">Jack Sprat</member> <member role="at large">Carol Smith</member> </committee> </event> <event type="Fair"> <event_title>Fall Festival Fundraiser</event_title> <committee> fundraising.xml <member role="chair">Sally Chair</member> <member role="secretary">John Helper</member> <member role="at large">Carol Smith</member> </committee> </event> <event type="Food"> <event_title>Donut Sale</event_title> <committee> <member role="chair">Ruth Member</member> <member role="secretary">Eric Serve</member> <member role="at large">Connie Adams</member> <member role="at large">Henry Assistant</member> </committee> </event> </events> Slide Set 5 97

  75. function handleXML(xml) { var titles = xml.getElementsByTagName("event_title"); var committees = xml.getElementsByTagName("committee"); var i = 0; var j = 0; var table = document.createElement("table"); Builds table of table.border = "5px"; fundraising events and the var row = table.insertRow(-1); chairs var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "<b>Event</b>"; cell2.innerHTML = "<b>Chair</b>"; for (i = 0; i < titles.length; i++) { var members = committees[i].getElementsByTagName("member"); for (j = 0; j < members.length; j++) { var attributes = members[j].attributes; if (attributes.getNamedItem("role").nodeValue == "chair") var chair = members[j].firstChild.nodeValue; } row = table.insertRow(-1); cell1 = row.insertCell(0); cell2 = row.insertCell(1); cell1.innerHTML = titles[i].firstChild.nodeValue; cell2.innerHTML = chair; } document.getElementById("mydiv").appendChild(table); 98 } http://www.cs.appstate.edu/~can/classes/5530/set5/fundraising.html

  76. Ajax and Security ● JavaScript is visible no matter its location (embedded, in a separate .js file, or generated by a script on the server) ● Users can look at your JavaScript, figure out how to call a script on the server, and pass the script fictitious data scorekeeper.php?score=2221 ● You can try to make your JavaScript less readable http://www.semdesigns.com/Products/Obfuscators/ Slide Set 5 99

  77. Ajax and Security ● Keep proprietary code on the server; never expose more code than is necessary ● Be aware that users can enter JavaScript code as a response and when that JavaScript is displayed on a browser, it is executed. <script type=”text/javascript”>window.location=www.malicious.com</script> – one solution to this problem is to convert sensitive html characters < and > to equivalents &lt; and &gt; Slide Set 5 100

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend