Faculty.cse.tamu.edu
INTRO to AJAXIntroduction to AJAXAJAX stands for Asynchronous JavaScript And XMLAJAX is not a programming languageIt is a framework/set of functions to allow developers features that JavaScript alone does not give themNot a programming language but group of technologies using HTML and CSS for presentation, JavaScript for dynamic content displayUses browser built-in XMLHttpRequest object to fetch data behind the scenesWe can request and receive data from a server without reloading the current pageSend data to a server without leaving the pageUses browser built-ins and JavaScript/HTML DOMsUsed to build asynchronous web applications (update parts of a web page without reloading the whole page)Best features of the language?makes fast and user-friendly websitesbrowser and platform-independentcan also use plain text or JSON (helps with JavaScript) to transport data instead of XMLIntroduction to XMLXML stands for eXtensible Markup Language.was designed to store and transport datatags are case sensitive <BOOK> != <book>was designed to be both human-and machine-readable (parsed)Example XML Files<catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.67</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.99</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book>AJAX Mechanics BasicsAJAX revolves around the use of the browser built-in XMLHttpRequest objectSome browsers (namely older versions of IE) might list it under a different name.The XMLHttpRequest can be constructed by processing user input (text fields, button presses, etc.) in JavaScript. It is then sent (to a particular URL) over HTTP, and returns the “page”. This “page” can be processed in JavaScriptHow is AJAX Asynchronous?pulling info from another server leaves us vulnerable if we have to wait for a responseslow connection, DB etc…the JavaScript code to be waiting, hanging, for it to finishAJAX (and specifically, the XMLHttpRequest) are asynchronous to allow the rest of the site/code to do whatever it needs to do without waiting for the HTTP response. make the request and the application proceedsusually we will want to at least be able to know what the response was (and probably process/display it). XMLHttpRequest is constructed with a callback function that executes when the request has finished. This function is just JavaScript, so you write a function that handles your request.Overall steps in using AJAX with an HTML page1. An event occurs in a web page (the page is loaded, a button is clicked)2. An XMLHttpRequest object is created by JavaScript3. The XMLHttpRequest object sends a request to a web server4. The server processes the request5. The server sends a response back to the web page6. The response is read by JavaScript7. Proper action (like page update) is performed by JavaScriptUsing The AJAX callback functionEvery XMLHttpRequest has a state, that takes one of 5 options:0: request not initialized 1: server connection established2: request received 3: processing request 4: request finished and response is readyThe object also has one function, onreadystatechange that is called each time the object transitions from one state to another. We can also check the status of the Request, for handling purposes.The callback functionclean versionfunction?loadDoc() {??var?xhttp =?new?XMLHttpRequest();? xhttp.onreadystatechange?=?function() {????if?(this.readyState?==?4?&&?this.status?==?200) {???? document.getElementById("demo").innerHTML?=?this.responseText;????}? };? xhttp.open("GET",?"ajax_info.txt",?true);? xhttp.send();}Breaking down the callback functionThe HTML houses import itemsdiv tag area for our “response test”where the acquired text will be placed EVERYTHING within the <div></div> is replaced!because of the “id”, not because of <div>call to our JavaScript/AJAX functionSetting up the HTML for AJAX features<!DOCTYPE?html><html><body><div?id="demo">??<h2>Let AJAX change this text</h2>??<button?type="button"?onclick="loadDoc()">Change Content</button></div></body></html>the request is placed in a JavaScript functionthis function is again called by something within the HTMLThe JavaScript/AJAX functionfunction?loadDoc() { ... // AJAX stuff here}within the function itself it:instantiates an XMLHttpRequestcreates a handler check to see if the request is finished, and then does some processingyes, first BEFORE (next)opens a connection to the data sourcehandler would identify this as a state change not coded in this examplerequests the datahandler would identify this as another state change not coded in this example EXCEPT the last stagethe data received is “responseText”the XMLHttpRequest object itself has a “responseText” attribute that captures all of the text that would be displayed to the screen ordinarilythe similar attribute, “responseXML” which lets the application parse the XML DOM in meaningful and powerful waysClean callback functionfunction?loadDoc() { // set up request OBJECT??var?xhttp =?new?XMLHttpRequest(); // set up hander to handle the various stages of the request? xhttp.onreadystatechange?=?function() {????if?(this.readyState?==?4?&&?this.status?==?200) {???? document.getElementById("demo").innerHTML?=?this.responseText;????}? }; // Open() establishes the connection with the server // This will succeed (and changes the state)? xhttp.open("GET",?"ajax_info.txt",?true); // request data? xhttp.send();}Replacing the HTML text with AJAXreplacing the HTML text will be done using the “id”Updating the HTML page with dataHTML<div?id="demo">...</div><table border=1px id="cdTable">AJAX Codedocument.getElementById("demo").innerHTML?=?this.responseText;document.getElementById("cdTable").innerHTML = table; //could have been this.responseTextThe various stages of the AJAX handlerhere is a little more on the various stages the handler can watch forDebugging the ReadyState of the handlerfunction loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { var demo = document.getElementById("demo"); //First time that this function is called (but is called manually) if (this.readyState == 0) { demo.innerHTML += "Request Not initialized"; } //Other states else if (this.readyState == 1) { demo.innerHTML += "Server connection Established"; } else if (this.readyState == 2) { demo.innerHTML += "Request received"; } else if (this.readyState == 3) { demo.innerHTML += "Processing request"; } if (this.readyState == 4) { //HTTP success if(this.status == 200) // 200 implies that the response contains a payload that // represents the status of the requested resource { demo.innerHTML += this.responseText; } //HTTP failure else if(this.status == 404) { demo.innerHTML += "NOT FOUND"; } } }; // ends inner function // request and send would be below xhttp.open("GET", "ajax_info.txt", true); // request data xhttp.send();}With the HTML file “AJAXIntro2.html” and the text files “button1_text.txt” and “button2_text.txt” write an AJAX method named “buttonClick” that takes a URL and function name and creates an XMLHttpRequest which will call the function passed in when the request is ready. Then create two JavaScript functions ‘functionOne’ and ‘functionTwo’ which take in an XMLHttpRequest object; ‘functionOne’ should append the contents of “button1_text.txt” to the ‘textBlockOne’ div element while ‘functionTwo’ should append the contents of “button2_text.txt” to the ‘textBlockTwo’ div element.The result should look similar to below:(files can be found here)InitialAfter clicking Button 1After clicking Button 1 then Button 2(For some reason, this might not work for Chrome, try Firefox, or (sadly IE) (possible Chrome fix)What to do with the data receivedwe need to determine what data will be sent backStringparse as needed using JavaScript string functionsXMLrequires us to determine the XML configurationlittle more interesting (use below)Gathering the data from the AJAX requestXML FileResult<CATALOG><CD><TITLE>Empire Burlesque</TITLE><ARTIST>Bob Dylan</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Columbia</COMPANY><PRICE>10.90</PRICE><YEAR>1985</YEAR></CD><CD><TITLE>Hide your heart</TITLE><ARTIST>Bonnie Tyler</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>CBS Records</COMPANY><PRICE>9.90</PRICE><YEAR>1988</YEAR></CD>…AJAX handler2632668673421function?loadDoc() {??var?xhttp =?new?XMLHttpRequest();??xhttp.onreadystatechange?=?function() {????if?(this.readyState?==?4?&&?this.status?==?200) { myFunction(this); }? };? xhttp.open("GET",?"cd_catalog.xml",?true);??xhttp.send();}function?myFunction(xml) {??var?i;??var?xmlDoc = xml.responseXML;??var?table="<tr><th>Artist</th><th>Title</th></tr>";??var?x = xmlDoc.getElementsByTagName("CD");??for?(i =?0; i <x.length;?i++) {???? table +=?"<tr><td>"?+??? x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue?+????"</td><td>"?+??? x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue?+????"</td></tr>";? }??document.getElementById("demo").innerHTML?= table;}AJAX can make a call to interact with a PHP page, as well as parse plaintext, JSON and HTMLWith the HTML file “AJAXIntro4.html” and the “library.xml” file from Exercise 3, write an AJAX method named “sortLibrary” that takes a URL and XML attribute name and creates an XMLHttpRequest which will fetch the XML file given by the url, store the elements of the given attribute, sort those elements, then display those elements in the ‘table’ HTML element with the id ‘cdTable.’ The result should look similar to below:Sort by ArtistSort by AlbumSort by Number of Songs Other informationIt is considered bad practice (according to w3) to have multiple functions that use an XMLHttpRequest in the JavaScript code Instead, you should have one function that takes in as a parameter another function that does something more specificnotice you are passing in a functionThis is to debug if a request is not returned or runs into a problemUsing one HttpRequest function for many instancesWhat documented support is available?Good documentations(Button Clicks) (CD Library)Resources (all pictures are from w3schools): (Tutorial with worked examples) (Tutorial) (example XML)(retrieving PHP) ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.