1
Asynchronous JavaScript And XML (AJAX)
- Asst. Prof. Dr. Kanda Runapongsa Saikaew
(krunapon@kku.ac.th)
- Dept. of Computer Engineering
Asynchronous JavaScript And XML (AJAX) Asst. Prof. Dr. Kanda - - PowerPoint PPT Presentation
Asynchronous JavaScript And XML (AJAX) Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Dept. of Computer Engineering Khon Kaen University 1 What is Common of these? Web sites Google Maps http://maps.google.com
1
Web sites
Google Maps http://maps.google.com Google Mail http://gmail.google.com Google Search http://www.google.com Flicks Photo Sharing http://flickr.com Social Bookmarking http://del.icio.us
2
3
4
AJAX: Asynchronous Javascript And
An architectural style (a high level
Make the Web become richer and
5
HTTP never intend to dynamically
Pages always reload, but never get
Users wait for the entire page to load
Single request/response restrictions
No middle ground between “this page”
6
People are using different computers
Hosting the data online is the most
Some people have no computer
A web application is the only practical
7
Many homes and offices now have
Server-side storage is cheap enough for
The technologies behind AJAX –
8
For developers, a modern web
A single set of code for all platforms Allow upgrade the application
Choose whatever programming
9
Developing rich applications on the
But it‟s actually a lot easier now to
As security concerns have
10
Application developers are usually
A web application is often more a
One of the great strengths of the
11
They let you drag boxes instead of
They keep page content fresh instead
They show meaningful animations
12
On February 18, 2005, Jesse-James
Garrett introduced “Ajax to label the
13
Applications, Not Just Web sites
Keeps user engaged and productive Socialize via the browser platform
Smooth, Continuous Interactions
JavaScript makes AJAX interaction feel
Live
Can be programmed to always show the
Supportive
AJAX Apps can monitor user actions and
proactively support whatever task the user‟s working on
Visual Effects
Animation that gets across a message about
what‟s happening and what the user can do next
Standards-based
AJAX makes the most of standard browser
features and avoid browser-specific features and plugins where possible
15
New Widgets
AJAX Widgets go beyond the standard
Sliders and progress indicators, built on
New Styles of Interaction
Drag-and-drop Keyboard shortcuts
16
Standards-based presentation using
Dynamic display and interaction using
Data interchange and manipulation
Asynchronous data retrieval using
JavaScript binding everything
17
An AJAX App uses an HTML
The document is continuously
Where possible, its XML-compliant
18
CSS enriches the display and, thanks
CSS can easily be manipulated with
With just one line of code, you can
19
AJAX communicates via HTTP Instead of returning full pages, the
Form submission is also used, no
20
The server is still required to perform
In some AJAX applications, it no
Leaving those things for the browser
21
Client-side programming language
Not Java, but from the same family
Java-like syntax Loosely-typed variables, dynamically
Functions are objects
Can be involved from outside a class
Can use OOP-like style, but not
22
The DOM exposes a web page to the
Programming recommendations
Use of “id” attribute to make finding
CSS styles applied using node‟s
Head1.className = „redhead‟;
Use of XHTML
23
Invisible frame, in line with other
IFrame owns the processing
24
XMLHttpRequest: DOM extensions
Issues: browser compatibility
Developer owns implementation, testing
Example: some web page displays
25
26
27
The browser hosts an application, not
Application code delivered to the
The server delivers data, not content
Data may be plain text, JavaScript
28
User/application interaction is
UI methapors like drag-and-drop
This is real coding and requires
Significant developer responsibility to
29
Google helped popularize, and
Increase usability of Web applications Rich Internet applications without
Save bandwidth Download only data you need Faster interfaces (sometimes)
30
Note these are not all specific to
Browser “back” button may not work
Browsers record static page visits
Increase browser code size
Response time affected
Difficult to debug
Processing logic both in client
31
Bookmarking state becomes difficult
JavaScript generates the page
Viewable source
Open to hackers or plagiarism
Server Load
Asynchronous request may be an expensive
Web analytics
Many web analytics solutions are based on
the paradigm of a new page being loaded whenever new content is displayed to the user
32
Dojo Toolkit http://dojotoolkit.org/ Google Web Toolkit http://code.google.com/webtoolkit/ PHP Ajax Frameworks http://ajaxpatterns.org/PHP_Ajax_Frameworks AJAX : The Official Microsoft ASP.NET Site http://www.asp.net/ajax/ Prototype JavaScript Framework http://prototypejs.org/
33
Javascript
Loosely typed scripting language JavaScript function is called when an
Glue for the whole AJAX operation
DOM
Represents the structure of XML and
API for accessing and manipulating
34
CSS
Allows for a clear separation of the
XMLHttpRequest
JavaScript object that performs
35
JavaScript object Adopted by modern browsers
Mozilla™, Firefox, Safari, and Opera
Communicates with a server via
XMLHttpRequest object works in the
Does not interrupt user operation
36
37
open(“HTTP method”, “URL”, syn/asyn):
Assigns HTTP method, destination URL, mode
send(content): Sends request including string
abort(): Terminates current request getAllResponseHeaders(): Returns
getResponseHeader(“header”): Returns
setRequestHeader(“label”,”value”): Sets
38
Onreadystatechange
Set with an JavaScript event handler that fires
at each state change
readyState – current status of request
0 = The request is not uninitialized 1 = The request has been loading 2 = The request has been loaded 3 = The request is in process 4 = The request is complete
Status
HTTP Status returned from server: 200 = OK 39
responseText
String version of data returned from the
responseXML
XML document of data returned from the
statusText
Status text returned from server
40
41
1. 1.
A Client t event t occurs rs // file display.html <html><head> <script src="clienthint.js"></script> </head> <body> <form> Company Name : <input type="text" id="txt txt1"onke keyu yup="sh showH wHin int(th this. is.va value)"> </form> <p><span id="txtHint"> Result will be list here.</span></p> </body></html>
42
ttpReq Request st object ct is create ted //clienthint.js (1/4) var xmlHttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp Http=Ge GetX tXmlHtt lHttpOb Obje ject() ct() if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; }
43
3. An XMLHttpR
pRequ eques est object is configured igured with h a callback lback function ion
4. XMLHttpReques
pRequest object ect makes es an async nc. request uest
//clienthint.js (2/4)
var url="getDa getData. a.php"+"?q= php"+"?q="+str+ r+"&s &sid="+ id="+ Math. h.rand random
(); // result from calling stateChanged function xmlHttp.onready lHttp.onreadystat atec echange hange=s =stat ateC eChan hanged; ged; xmlHtt lHttp.open("G p.open("GET",url, url,true); rue); xmlHtt lHttp.sen p.send(null); d(null); }
44
//clienthint.js (3/4) function GetXmlHttpObject(){ var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
45
pRequest object ect call lls call llbac ack() () function n and proces esses es the result lt
The XMLHttpRequest object was configured to
call the stateChanged() function when there is a state change to the readyState of the XMLHttpRequest object
7. The HTML DOM is updated
function stateChanged() { if (xmlHttp. p.readySt readyState== ate==4) ) { document ument.getEl getElem ementBy entById("txtH d("txtHint int") .innerHTML=xmlHttp.responseText; }}
46
<!-- getData.php (1/3) --> <?php // Connect to database and fetch result into array name. $name = array("Amazon 24689", "Google 13579", "Holiday Inn 123456", "Bevery Hills 987665", "Rhyme & Reason Inc. 966640", "RRR Advertising Inc. 466136", "RIVIERA HOTELS 169706", "RIVIERA HOTELS 928748", "RRR Advertising Inc. 77165", "Yahoo Inc. 369864"); $q=$_GET["q"]; // get the q parameter from URL
47
<!-- getData.php (2/3) --> //lookup all hints from array if length of q>0
ide script t returns ns the resul ults ts if (strlen($q) > 0){ $hint=""; for($i=0; $i<count($name); $i++) { if (strtolower($q)==strtolower(substr($name[$i],0,strlen($q)))) { if ($hint=="") { $hint=$name[$i]; } else { $hint=$hint."<br/>".$name[$i]; } } } }
48
<!-- getData.php (3/3) --> //Show Hint if ($hint == ""){ $response="Not found!"; } else{ $response=$hint; } //output the response echo $response; ?>
49
50
51
To build AJAX applications, we can
Dojo and JSON are two very different
Both of them can significantly
52
Dojo is a set of powerful Javascript
Aside from providing Ajax functionality,
String manipulation DOM manipulation Drag-and-drop support Data structures, such as lists, queues, and
stacks
53
JSON is a Java library that helps
JSON is designed to be used in
Since server side can be written in a
54
Mozilla FireBug debugger (add-on)
This is the most comprehensive and most useful
JavaScript debugger
This tool does things all other tools do and more
Mozilla JavaScript console Mozilla DOM inspector (comes with Firefox
package)
Mozilla Venkman JavaScript debugger (add-on) Mozilla LiveHTTPHeaders HTTP monitor
(similar to NetBeans HTTP monitor)
55
Spy on XMLHttpRequest traffic JavaScript debugger for stepping through code one
line at a time
Inspect HTML source, computed style, events, layout
and the DOM
Status bar icon shows you when there is an error in a
web page
A console that shows errors from JavaScript and CSS Log messages from JavaScript in your web page to
the console (bye bye "alert debugging")
An JavaScript command line (no more "javascript:" in
the URL bar)
56
Wikipedia, “Ajax (programming)”,
UW Business School, “AJAX Overview”,
Jesse-James Garrett, “Ajax: A New
57
Zarar Siddiqi, “Using Dojo and JSON to
Michael Mahemoff, “Ajax Design
58