You are on page 1of 10

Google Suggest

http://labs.google.com/suggest
Lecture 17: Ajax
(Asynchronous
JavaScript And XML)
Wendy Liu
CSC309F Fall 2007

1 2

Spinning Wheel Progress Indicator

Low-level View

The Basics

3 4

1
Classic vs. Ajax Synchronous vs. Asynchronous

5 6

Overview of Ajax XMLHttpRequest


It is not a new programming language, but a new way JavaScript object
(technique) to use existing standards
To create better, faster, and more user-friendly and interactive Provide two views of the response
web applications
String (text) and XML
Based on JavaScript and HTTP requests
Uses JavaScript as its programming language Capable
of issuing GET, POST, HEAD, PUT,
Uses the XMLHttpRequest object to communicate directly with DELETE, OPTIONS requests
the server
Trades data with a web server without reloading the page Security limitations apply
Uses asynchronous data transfer (via HTTP requests)
between the browser and the web server Same point of origin
Allowing web pages to request small bits of information from the Can only connect to same domain as currently loaded
server instead of whole pages
page
It is a browser technology independent of web server
software
7 8

2
XMLHttpRequest Properties onreadystatechange
Receiving data (handle response) Defines a function to receive data returned by
onreadystatechange
the server after a request is sent
readyState Must be set before sending request

responseText The following code defines a function for this

responseXML
purpose (with an empty body for now)
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
// code for receiving response data
}
9 10

readyState Update the Function


This property holds the status of the server's xmlhttp.onreadystatechange=function()
response {
Each time the readyState changes, the
if (xmlhttp.readyState==4)
onreadystatechange function will be executed
{
State description
// Get the data from the server's response
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
11 12

3
responseText responseXML
Retrieve
text data returned by the server Retrieve document data returned by the server
Type: DOMString (readonly) Type: Document (readonly)
xmlhttp.onreadystatechange=function()
{ var xmldoc=xmlhttp.responseXML.documentElement;
if (xmlhttp.readyState==4)
{ You can access it as a DOM document
document.getElementById(formentry).value = As you did in A1
xmlhttp.responseText;
}
}
13 14

XMLHttpRequest Methods Execute the Ajax Function


Asking for data (send request) Want it to run "behind the scenes"
open() <script type="text/javascript">
Two required arguments function myajax()
method (GET, POST, PUT, DELETE, HEAD, OPTION) { . . . /* all of the code from before */ . . . }
server-side URI
</script>
send()
<form>
One argument
<input type="text" onkeyup="myajax();"
data to be sent (DOMString or Document)
name="userdata" />
null for GET

can be omitted <input type="text" id="formentry" />


</form>
15 16

4
The Basic Ajax Process
JavaScript
Define an object for sending HTTP requests
Initiate request
Get request object
Examples Designate a request handler function
Supply as onreadystatechange attribute of request
Initiate
a GET or POST request
Putting it Together Send data

Handle response
Waitfor readyState of 4 and HTTP status of 200
Extractreturn text with responseText or responseXML
Do something with result

17 18

The Basic Ajax Process (contd) Define a Request Object


HTML var request;
Loads JavaScript
Designates control that initiates request
function getRequestObject() {
if (window.XMLHttpRequest) {
Gives ids to input elements that will be read by
script return(new XMLHttpRequest());
} else {
return(null);
}
} Browsers that support it

19 20

5
Initiate Request Handle Response
function sendRequest() { function handleResponse() {
request = getRequestObject(); Response handler if (request.readyState == 4) {
function name
request.onreadystatechange =
alert(request.responseText);
handleResponse;
request.open("GET", "message-data.html", }
true); }
request.send(null);
} URL of server-side
resource Text of server Response is returned from server
response (handler is invoked multiple times)

Don't wait for response (Default). Data (null for GET)


Send request asynchronously

21 22

Complete JavaScript Code


XHTML Code (show-message.html)
(show-message.js)
var request; <!DOCTYPE html PUBLIC "..." "..."
function getRequestObject() {
if (window.ActiveXObject) {
<html xmlns="http://www.w3.org/1999/xhtml">
return(new ActiveXObject("Microsoft.XMLHTTP")); <head><title>Ajax: Simple Message</title>
} else if (window.XMLHttpRequest) { <script src="show-message.js"
return(new XMLHttpRequest());
} else {
type="text/javascript"></script>
return(null); </head>
} <body><center>
} <table border="1" bgcolor="gray">
function sendRequest() { // called in XHTML
request = getRequestObject(); <tr><th>Ajax: Simple Message</th></tr>
request.onreadystatechange = handleResponse; </table>
request.open("GET", "message-data.html", true); <form action="">
request.send(null);
} <input type="button" value="Show Message"
function handleResponse() { onmouseover="sendRequest()"/>
if (request.readyState == 4) { </form>
alert(request.responseText);
} </center></body></html>
} 23 24

6
XHTML Code (message-data.html) The Basic Process: Results
Some random message

25 26

Cross-Browser XMLHttpRequest
function getRequestObj() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) { // Internet Explorer
try { High-level View
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { Frameworks
alert("Your browser does not support AJAX!");
return null;
}
}
} return xmlHttp;
}
27 28

7
Motivation Client-Side Frameworks I
Challenges of Ajax Rico
Browser compatibilities Designed for drag-and-drop actions, data grids,
Repeated coding effort and what they term cinematic effects (moving
widgets, fading a div, and so on)
http://openrico.org

scriptaculous
Animation framework, drag and drop, Ajax
controls, DOM utilities, and unit testing
http://script.aculo.us/

29 30

Client-Side Frameworks II Client-Side Frameworks III


Dojo TIBET
Focused on usability Client-side middleware and WYSIWYG tools
For constructing web service clients, web portals, and
http://www.dojotoolkit.org standalone or embedded device web applications
qooxdoo (pronounced [ku:ksdu:]) Provide support for Web Services, low-level protocols,
and pre-built wrappers
Sophisticated widgets that allow a thin
Google, GMail, Zoe, Amazon, Blogger, Syndic8, Meerkat,
application to incorporate rich UI features XIgnite
http://qooxdoo.oss.schlund.de Fully interactive browser-based IDE that simplifies
development, debugging, and unit testing
http://www.technicalpursuit.com

31 32

8
Simple Wrappers for XMLHttpRequest Client-Side Toolkits
SACK (Simple Ajax Code Kit) Yahoo User Interface Library (YUI)
Free JavaScript toolkit with some Ajax support
http://twilightuniverse.com/projects/sack/
http://developer.yahoo.com/yui/
XHConn Google
http://xkr.us/code/javascript/XHConn Google Ajax API
Search, Feed, Map API
http://code.google.com/apis/ajax/
Google Mapplet
http://code.google.com/apis/maps/documentation/mapplets
Google Web Toolkit
Write code in Java, translate it to JavaScript
http://code.google.com/webtoolkit/
33 34

Server-side Framework I Server-side Framework II


JSON (JavaScript Object Notation) SWATO (Shift Web Application TO)
Text format used to exchange data Allows you to call server-side Java from a
Like XML, but easier to manipulate browser
http://json.org A set of reusable and well-integrated Java/JavaScript
library
Direct Web Remoting (DWR)
Uses JSON to marshal data between the client
Allows Javascript in a browser to interact with and server
Java on a server and helps you manipulate web
https://swato.dev.java.net/doc/html/
pages with the results
http://getahead.org/dwr/

35 36

9
Server-side Framework III
Ruby on Rails
Allow rapid development of Web-based
applications
Rails has good support for Ajax with several
Correction: REST
built-in JavaScript libraries that wrap many
common features
The original slide is correct
http://www.rubyonrails.org

37 38

Actions (Verbs)
Controllers cannot have arbitrary verbs, only
these:
POST
Create - create a new resource
GET
Retrieve - retrieve a representation of a resource
PUT
Update - update a resource
DELETE
Delete - delete a resource
39

10

You might also like