AJAX 1 2 Introduction AJAX: Asynchronous JavaScript and XML Popular in 2005 by Google Create interactive web applications Exchange small amounts of data with the server behind the scenes No need to reload the whole page whenever a user requests a change Asynchronous: loading does not interfere with normal page loading 3 4
5 6 Overview AJAX: Asynchronous JavaScript and XML Not a new programming language Use existing techniques to create better, faster, and interactive web applications JavaScript + HTML/XHTML/XML JavaScript: programming language Communicate with the server Asynchronous data transfer (HTTP requests) between browser and server XML: Small bits of information sent between browser and serve Trades data with a web server without reloading the page Changes to the underlying data are immediately reflected in the web page Allow web pages to request small bits of information from the server, instead of whole pages Usage: Live search 7 8
Usage: voting Overview - techniques JavaScript + HTML/XHTML/XML JavaScript:XMLHTTPRequest object communicate with the server Send HTTP request Receive HTTP response Handle the response Methods: open Define the method used (GET or POST), URL to send the request, and how the request, whether synchronous or asynchronous, is sent. send Sends the request to the server Properties: 9 10 XMLHttpRequest Two ways to use the object Synchronous usage Wait for the response, hold processing until a response is received Asynchronous usage Continue processing, interrupt once a response is received Security limitations: Can only connect to same domain as currently loaded page (same point of origin) XMLHttpRequest Methods Sending request (asking for data) 2 methods: open( GET, time.php, true) method First argument: GET or POST Second argument: URL of the server-side script Third argument: true means that the request should be handled asynchronously false means that it is a synchronous request Hold up the processing until a request is received send() method Sends the request to the server 11 12
XMLHttpRequest Properties: onreadystatechange Returns or sets the event handler for asynchronous requests readystate Returns a code representing the state of the request responsetext Returns the HTTP response as a string responsexml Returns the HTTP response as an XML DOM object status Returns the HTTP status code statustext Returns the text that describes what a particular HTTP status code means 13 onreadystatechange Defines a function to receive data returned by the server after a request is sent Must be set before sending request Code: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = myfunction() { // code for receiving response data 14 readystate This property holds the status of the server s response Each time the readystate changes, the onreadystatechange function will be executed readystate Property: state description 0: the request is not initialized Object has been created, but not yet been initialized 1: the request has been set up Has been initialized 2: the request has been sent The send method has been called, waits for the return of the status code 3: the request is in process Some of the data has been received, but not all 4: the request is complete Update the function Code: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = myfunction() { if (xmlhttp.readystate==4) { // code for receiving response data 15 16
responsetext and responsexml Retrieve data returned by the server responsetext: Returns the HTTP response as a string ptext.value = xmlhttp.responsetext; responsexml: Returns the HTTP response as an XML DOM object Var xmldoc = xmlhttp.responsexml.documentelement; Access it as a DOM document status: HTTP status code (200, 404, ) Example 17 18 Basic Process Define an object for sending HTTP requests Initiate request Get request object Designate a request handler function Initiate a GET or POST request Send data Handle response Wait for readystate==4 Extract returned data Programme your code for the receiving data Define XMLHttpRequest Object Different browsers uses different methods to create the XMLHttpRequest object Used to communicate with the server Firefox, IE 7 xmlhttp = XMLHttpRequest(); IE 6, IE5 xmlhttp=new ActiveXObject( Microsoft.XMLHttp"); 19 20
In the body: First Example <form name="myform"> <label> Name: </label> <input type="text" name="username" onblur="ajaxfunction()" /> </form> <p name="ptext" id="ptext"> </p> 21 First Example function ajaxfunction() { xmlhttp=null; if (window.xmlhttprequest) { head xmlhttp section: = new XMLHttpRequest(); function ajaxfunction() else if (window.activexobject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); if (xmlhttp!= null) { xmlhttp.onreadystatechange = statechange; xmlhttp.open("get", "time.php", true); xmlhttp.send(null); else { alert("your browser does not support XMLHTTP."); 22 First Example head section: function ajaxfunction() function statechange() { if ( (xmlhttp.readystate == 4) &&(xmlhttp.status == 200) ) { ptext.innerhtml = "The current time is: " + xmlhttp.responsetext; alert(xmlhttp.responsetext); First Example: time.php <?php echo date("h:i:s");?> 23 24
Example 2: Read a textfile Use an XMLHttpRequest to retrieve and display content of a file 25 XML File XML: Extensible markup language Plain text Create your own tags Design to transport and store data Separates data from HTML A start tag and an end tag surrounding the content of an element <root> <child> <subchild>. </subchild> </child> <child> </child> </root> 26 Example: Book Root element: <collection> <book>: 3 children: (3 child elements) <title>, <author>, <year> <title> is a start-tag </title> is an end-tag <title> A First Course in Database Systems</title>: is an element A First course in Database Systems: element content Code Code XML Tree Element: <title> Root element <collection> parent child Element: <book> siblings Element: <author> Element: <year> 27 28
XML DOM Defines a standard way for accessing and manipulating XML documents DOM: Views XML documents as a treestructure xmldoc.getelementsbytagname( xmlnam e )[0].childNodes[0].nodeValue Book.xml <book> <title> A First Course in Database Systems</title> <author> Jeffrey D. Ullman </author> <author> Jennifer Widom </author> <year> 2002 </year> </book> getelementsbytagname("title")[0] <title> A First </title> getelementsbytagname("title")[0].childnod es[0].nodevalue A First Course in Database Systems 29 30 Book.xml <book> <title> A First Course in Database Systems</title> <author> Jeffrey D. Ullman </author> <author> Jennifer Widom </author> <year> 2002 </year> </book> AJAX: XML Data Using responsetext: Example3a.html divtext.innertext = xmlhttp.responsetext; getelementsbytagname("author")[0] <author> Jeffrey D. Ullman </author> getelementsbytagname("author")[1] <author> Jennifer Widom </author> 31 32
AJAX: XML Data Using responsexml Parse as XML document (Example3b.html) Modifications Display author names tmp = "<table border='1'> "; data = xmlhttp.responsexml.documentelement. getelementsbytagname("book"); for (i=0;i<data.length;i++) { data2 = data[i].getelementsbytagname("title"); tmp = tmp + "<td>" + data2[0].childnodes[0].nodevalue + "</td>"; tmp = tmp + "</tr>" 33 34 XML XML data Web services use XML to communicate Db sometimes return query as XML Pros: Human-readable, platform-independent Self-documenting format Cons: Bulky syntax, can decrease performance JSON 35 36
JSON Syntax JavaScript Object Notation Syntax for storing and exchanging text information Use the build-in JavaScript function eval() to produce JavaScript objects Cf: XML: use XML DOM to loop through the document Quicker to read and write 37 38 AJAX + JSON function statechange() { if (xmlhttp.readystate == 4) { if (xmlhttp.status == 200) { var t = eval('('+ xmlhttp.responsetext + ')'); divtext.innerhtml = t.book[0].title + " " + t.book[0].author; 39 40
Concerns Back button? Alert users of background activity? Reliance on JavaScript Implemented differently by different browsers Web statistics Number of page loading XMLHttpRequest Level 2 41 42 Intro readystatechange event: Lacked a way to communicate upload progress XMLHttpRequest level 2 Introduces progress events loadstart, progress, abort, error, load, loadend 43 Example <body onload="loaddata('bigfile.zip')"> <p id="ddata"> </p> </body> var request; var progressbar; function loaddata(afile) { request = new XMLHttpRequest(); request.onloadstart = showprogressbar; request.onprogress = updateprogressbar; request.onloadend = hideprogressbar; request.open("get", afile, true); request.send(null); 44
function showprogressbar() { progressbar = document.createelement("progress"); progressbar.value = 0; progressbar.max = 100; document.body.appendchild(progressbar); function updateprogressbar(e) { if (e.lengthcomputable) { progressbar.value = e.loaded / e.total * 100; ddata.innerhtml = progressbar.value + '%'; function hideprogressbar() { document.body.removechild(progressbar); 45 46 Summary AJAX idea JavaScript + Data Synchronous vs asynchronous request Pros and cons 47