Monday, May 27, 2013

Ajax basics

http://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/Ajax_Basics.html
The classical example of Ajax is google map
Ajax uses a JavaScript object called XMLHttpRequest

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(methodurlisAsyn): 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(paramvalue): 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<title>Hello, Ajax</title>
</head>
 
<body>
  <h2>Hello, Ajax</h2>
  <!-- holder for Ajax response text -->
  <div id="ajaxText"></div>
  <a href="test" onclick="return loadAjaxText()">SEND</a>
</body>
 
<script type="text/javascript">
 
// Load Ajax responseText into element with id="ajaxText"
function loadAjaxText() {
   // Allocate an XMLHttpRequest object
   if (window.XMLHttpRequest) {
      // IE7+, Firefox, Chrome, Opera, Safari
      var xmlhttp=new XMLHttpRequest();
   } else {
      // IE6, IE5
      var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   // Set up the readyState change event handler (EVENT HANDLER)
   xmlhttp.onreadystatechange = function() {
      if ((this.readyState == 4) && (this.status == 200)) {
         if (this.responseText != null) {
            // Load the responseText into element with id="ajaxText"
            var outElm = document.getElementById('ajaxText');
            outElm.innerHTML = this.responseText;
         }
      }
   }
   // Open an asynchronous POST connection and send request
   xmlhttp.open("POST", "HelloAjax.txt", true);
   xmlhttp.send();
   return false;  // Do not follow hyperlink
}
</script>
</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", urlisAync) 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 (statusCodeof OK) indicates successful request; the response message can be retrieved from the responseText. In this example, we load the responseText into the element withid="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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html>
<head>
<title>Hello, Ajax</title>
</head>
 
<body>
  <h2>Hello, Ajax</h2>
  <table>
    <tr>
      <td><textarea id="inText" name="inText" cols="40" rows="5">Enter your text here...</textarea></td>
      <td><textarea id="ajaxText" name="ajaxText" cols="40" rows="5"></textarea></td>
    </tr>
   </table>
   <a href="test" onclick="return loadAjaxText()">SEND</a>
</body>
 
<script type="text/javascript">
// Append Ajax responseText into element with id="ajaxText"
function loadAjaxText() {
   // Allocate an XMLHttpRequest object
   if (window.XMLHttpRequest) {
      // IE7+, Firefox, Chrome, Opera, Safari
      var xmlhttp=new XMLHttpRequest();
   } else {
      // IE6, IE5
      var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   // Set up the readyState change event handler
   xmlhttp.onreadystatechange = function() {
      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
         }
      }
   }
   // Open an asynchronous POST connection and send request
   xmlhttp.open("POST", "HelloAjax.php", true);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //necessary 
   var inTextElm = document.getElementById('inText');
   xmlhttp.send("inText=" + inTextElm.value);
   return false;  // Do not follow hyperlink
}
</script>
</html>
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", urlisAync) 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
2
3
4
5
6
<?php
// Echo back the POST parameter inText=xxx
if (isset($_POST['inText'])) {
  echo ">> {$_POST['inText']}\n"; //responseText

}
?>
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<title>Hello, Ajax</title>
</head>
 
<body>
  <h2>Hello, Ajax with XML</h2>
  <!-- holder for Ajax response text -->
  <div id="ajaxText"></div>
  <a href="test" onclick="return loadText()">SEND</a>
</body>
 
<script type="text/javascript">
function loadText() {
   if (window.XMLHttpRequest) {
      // IE7+, Firefox, Chrome, Opera, Safari
      var xmlhttp=new XMLHttpRequest();
   } else {
      // IE6, IE5
      var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange = function() {
      if ((this.readyState == 4) && (this.status == 200)) {
         if (this.responseXML != null) {
            var xmlDoc = this.responseXML;
            var txt = "";
            // Retrieve all the "title" elements from the XML document
            var titleElms = xmlDoc.getElementsByTagName("title");
            for (i = 0; i < titleElms.length; i++) {
               txt += titleElms[i].childNodes[0].nodeValue + "<br />"; //processing XML
            }
            document.getElementById("ajaxText").innerHTML = txt;
         }
      }
   }
   xmlhttp.open("POST", "HelloAjax.xml", true);
   xmlhttp.send();
   return false;
}
</script>
</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.

No comments:

Post a Comment