AJAX
2018/19 COMP3322A Modern Technologies on WWW

Contents
•
What is AJAX?
•
Demo 1
–
Our Registration Form
•
Overview of XML
•
Overview of JSON
•
Demo 2
–
Our Registration Form

AJAX
a
.

Consider a webpage that displays the server’s time

Consider a webpage that displays the server’s time

The XMLHttpRequest Object
•
The XMLHttpRequest object is the core of AJAX.
•
How AJAX works:
•
At client-end (JavaScript)
•
To send an HTTP request,
create
an XMLHttpRequest object.
•
Register a callback function to the
onreadystatechange
property of the XMLHttpRequest
object.
•
Use the
open()
and
send()
method of XMLHttpRequest object to sent the request to
server.
•
Use either GET or POST method.
•
Use either synchronous or asynchronous mode.
•
When the response arrives, the callback function is triggered to act on the data.
•
Usually rendering the web page using the DOM, that eliminates page refresh.

The XMLHttpRequest Object
•
All modern browsers support the XMLHttpRequest object.
•
However, old versions of Internet Explorer (5/6) use an ActiveX
object instead.
•
If you do not want to support old versions, just simple declare the
object.
// Old compatibility code, no longer needed.
if
(
window
.
XMLHttpRequest
) {
// Mozilla, Safari, IE7+ ...
httpRequest
=
new
XMLHttpRequest
();
}
else if
(
window
.
ActiveXObject
) {
// IE 6 and older
httpRequest
=
new
ActiveXObject
(
"Microsoft.XMLHTTP"
);
}
var
httpRequest
=
new
XMLHttpRequest
();
if
(!
httpRequest
) {
// do something to alert user
}

Open() & send()
•
To define the request, use open()
open
(method, url, async)
•
where:
•
method: the request type GET or POST
•
url: the server resource
•
async: [default] true if asynchronously; false if synchronously.
•
To send the request, user send()
send
() or
send
(string)
•
string: only used for POST
•
To use POST to send data, you may have to set the MIME type of the request
too.
httpRequest
.
open
(
'GET'
,
'process.php?name=value'
,
true
);
httpRequest
.
send
();
httpRequest
.
open
(
'POST'
,
'process.php'
,
true
);
httpRequest
.
setRequestHeader
(
'Content-Type'
,
'application/x-www-form-urlencoded'
);
httpRequest
.
send
(
'name=value'
);

XMLHttpRequest Object Properties
Property
Description
onreadystatechange
Registers a function to be called
when the readyState
property changes
readyState
Holds the status of the XMLHttpRequest.
0: request not initialized
1
: server connection established
2: request received
3: processing request
4
: request finished and response is ready
responseText
Returns the response data as a string
responseXML
Returns the response data as XML data
status
Returns the status-number of a request, e.g, 200, 302, 404, ..
statusText
Returns the status-text
function
callback
() {
if
(
receive good response
)
:
else
:
}
httpRequest
.
onreadystatechange
=
callback
;
Register a callback function to the
onreadystatechange
property.
