You are on page 1of 8

yet another insignificant programming notes...

| HOME

TABLE OF CONTENTS (HIDE)


1. Introduction
2. Examples

2.1 Example 1: First Ajax


2.2 Example 2: Ajax with PHP
2.3 Example 3: Processing XML Document

3. Ajax Frameworks

AJAX

Basics
1. Introduction
The term "Ajax" was first mentioned in 2005, originally stands for "Asynchronous
JavaScript and XML". It has since gone beyond XML, and currently serves as a client-side
technology for JavaScript to transfer data between browser and server in the
background aynchronously, so as to provide better responsiveness. The classical
example of Ajax is google map.
Ajax uses a JavaScript object called XMLHttpRequest, which contains a set of properties
(or variables) and methods.
To create an XMLHttpRequest object, however, is browser dependent:
All browsers except IE: new XMLHttpRequest()
IE 5: new ActiveXObject("Microsoft.XMLHTTP")
IE 6+: new ActiveXObject("Msxml2.XMLHTTP") (???)
The properties are:

readyState : 0: unitialized; 1: loading; 2: Loaded; 3: Interactive; and 4:


completed.

onreadystatechange : for specifying an event handler for the change in


readyState.

responseText and responseXML : The response returned by the server in


text and XML format.

status and statusText : The status code (e.g., 200, 404) and status message
(e.g., OK, Page not found).
The methods are:

open(method, url, isAsyn) : Open an HTTP connection with the specified


method (GET or POST), url, and whether the request should be handled
asynchronously (true or false). Asynchronous request run in the background and

does not freeze the browser. Using async request is always recommended,
except short and small request.

setRequestHeader(param, value) : Set the request header for the given


param=value pair.

send(params) : send the GET/POST key=value parameters to the server.


abort() : abort the current request.
getAllResponseHeader() : returns all headers as a string.
getResponseHeader(param): returns the value of given param as a
string.

2. Examples
2.1 Example 1: First Ajax
In this example, we use Ajax to send a POST request asynchronously to request for a
text file.

HelloAjax.html
1<!DOCTYPE html>
2<html>
3<head>
4<title>Hello, Ajax</title>
5</head>
6
7<body>
8 <h2>Hello, Ajax</h2>
9 <!-- holder for Ajax response text -->
10 <div id="ajaxText"></div>
11 <a href="test" onclick="return loadAjaxText()">SEND</a>
12</body>
13
14<script type="text/javascript">
15
16// Load Ajax responseText into element with id="ajaxText"
17function loadAjaxText() {
18 // Allocate an XMLHttpRequest object
19 if (window.XMLHttpRequest) {
20
21

// IE7+, Firefox, Chrome, Opera, Safari

var xmlhttp=new XMLHttpRequest();


22 } else {
23
// IE6, IE5
24
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
25 }
26 // Set up the readyState change event handler
27 xmlhttp.onreadystatechange = function() {
28

if ((this.readyState == 4) && (this.status == 200)) {

29

if (this.responseText != null) {

30

// Load the responseText into element with id="ajaxText"

31

var outElm = document.getElementById('ajaxText');

32

outElm.innerHTML = this.responseText;

33

34

35 }
36 // Open an asynchronous POST connection and send request
37 xmlhttp.open("POST", "HelloAjax.txt", true);
38 xmlhttp.send();
39 return false; // Do not follow hyperlink
40}
41</script>
42</html>

HelloAjax.txt
This is the Response Text of Ajax Request!!!

You need to run this example under a HTTP server (e.g., Apache) as it sends a HTTP
POST request.
The client-side HTML contains a <div>, to be used as placeholder for the response text.
It also contains a hyperlink to trigger the Ajax request (the JavaScript function
loadAjaxText()).
The steps in using Ajax, in JavaScript function loadAjaxText() are:
1. Allocate an XMLHttpRequest object, via new XMLHttpRequest() (for all browsers
except IE) or new ActiveXObject("Microsoft.XMLHTTP") (for IE).
2. Open a GET or POST connection to the server, via open("GET|POST", url, isAync)
method. In this case, we request for a text file called "HelloAjax.txt".
3. Invoke send() to send the request to the server.
4. Provide the event handler onreadystatechange to handle the readyState change
event. The readyState of 4 indicates Ajax transfer completed; status of 200
(statusCode of OK) indicates successful request; the response message can be
retrieved from the responseText. In this example, we load the responseText into
the element with id="ajaxText".

Why Ajax (Instead of an Ordinary HTTP Form POST request)?


Asynchronous Request for Better Responsiveness : Without Ajax with
asynchronous request, the browser will freeze (and hang) while processing the request.
On the other hand, with the asynchronous request in the background, the browser
(JavaScript) do not have to wait for the response and can process other tasks. The
onreadystatechange() handler will be called back when the readyState changes (e.g.,
transfer completed).

No Reloading of Page : the Ajax request is run in the background, without the
need to reload the page.

2.2 Example 2: Ajax with PHP


In this example, we trigger an Ajax POST request to a PHP page to obtain dynamic
response.

HelloAjaxPHP.html
1<!DOCTYPE html>
2<html>
3<head>
4<title>Hello, Ajax</title>
5</head>
6
7<body>
8 <h2>Hello, Ajax</h2>
9 <table>
1
0

<tr>
<td><textarea id="inText" name="inText" cols="40" rows="5">Enter your text

1here...</textarea></td>
1
<td><textarea id="ajaxText" name="ajaxText" cols="40"
1rows="5"></textarea></td>
2

</tr>

1 </table>
3 <a href="test" onclick="return loadAjaxText()">SEND</a>
1</body>
4
1<script type="text/javascript">
5// Append Ajax responseText into element with id="ajaxText"
1function loadAjaxText() {
6 // Allocate an XMLHttpRequest object
1 if (window.XMLHttpRequest) {
7

// IE7+, Firefox, Chrome, Opera, Safari

var xmlhttp=new XMLHttpRequest();


8 } else {
1
// IE6, IE5
9
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
2 }
0 // Set up the readyState change event handler
2 xmlhttp.onreadystatechange = function() {
1
2
2

if ((this.readyState == 4) && (this.status == 200)) {


if (this.responseText != null) {
var ajaxElm = document.getElementById('ajaxText');

ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front

3
2

}
}

4 }
2 // Open an asynchronous POST connection and send request
5 xmlhttp.open("POST", "HelloAjax.php", true);
2 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
6 var inTextElm = document.getElementById('inText');
2 xmlhttp.send("inText=" + inTextElm.value);
7 return false; // Do not follow hyperlink
2}
8</script>
2</html>
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2

4
3
4
4
4
5
4
6

The client-side HTML contains two <textarea>s, for the input and output respectively. It
also contains a hyperlink to trigger the Ajax request (the JavaScript function loadText()).
The steps in using Ajax, in JavaScript function loadText() are:
1. Allocate an XMLHttpRequest object, via new XMLHttpRequest() (for all browsers
except IE) or new ActiveXObject("Microsoft.XMLHTTP") (for IE).
2. Open a GET or POST connection to the server, via open("GET|POST", url, isAync)
method.
3. Set the HTTP request headers, if needed. For example, you need to set the
HTTP request header " Content-type" to "application/x-www-form-urlencoded" if
you are sending POST data.
4. Invoke send(data) to send the POST request with query parameters to the
server.
5. Provide the event handler onreadystatechange() for the readyState change
event. The readyState of 4 indicates Ajax transfer completed; status of 200
(statusCode of OK) indicates successful request; the response message can be
retrieved from the responseText.

Server-side Program: HelloAjax.php


1<?php
2// Echo back the POST parameter inText=xxx
3if (isset($_POST['inText'])) {
4 echo ">> {$_POST['inText']}\n";
5}
6?>

The server-side program HelloAjax.php handles a POST request with parameter


inText=message, and echos back the input message.

2.3 Example 3: Processing XML Document


HelloAjaxXML.html
1<!DOCTYPE html>
2<html>
3<head>
4<title>Hello, Ajax</title>

5</head>
6
7<body>
8 <h2>Hello, Ajax with XML</h2>
9 <!-- holder for Ajax response text -->
10 <div id="ajaxText"></div>
11 <a href="test" onclick="return loadText()">SEND</a>
12</body>
13
14<script type="text/javascript">
15function loadText() {
16 if (window.XMLHttpRequest) {
17
// IE7+, Firefox, Chrome, Opera, Safari
18
var xmlhttp=new XMLHttpRequest();
19 } else {
20
// IE6, IE5
21
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
22 }
23 xmlhttp.onreadystatechange = function() {
24
if ((this.readyState == 4) && (this.status == 200)) {
25
if (this.responseXML != null) {
26

var xmlDoc = this.responseXML;

27

var txt = "";

28

// Retrieve all the "title" elements from the XML document

29

var titleElms = xmlDoc.getElementsByTagName("title");

30

for (i = 0; i < titleElms.length; i++) {

31

txt += titleElms[i].childNodes[0].nodeValue + "<br />";

32

33

document.getElementById("ajaxText").innerHTML = txt;

34

35

}
36 }
37 xmlhttp.open("POST", "HelloAjax.xml", true);
38 xmlhttp.send();
39 return false;
40}
41</script>
42</html>

The XML File: HelloAjax.xml


<bookstore>

<book>
<title>Java For Dummies</title>
<author>Tan Ah Teck</author>
</book>
<book>
<title>Java For More Dummies</title>
<author>Tan Ah Teck</author>
</book>
</bookstore>

3. Ajax Frameworks
Many frameworks are available on top of JavaScript and Ajax.

jQuery
A JavaScript framework that provides an Ajax framework and other utilities.
[TODO]

REFERENCES & RESOURCES


1. [TODO]
Latest version tested: ???
Last modified: December, 2012
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan
(ehchua@ntu.edu.sg) | HOME

You might also like