Introduction

AJAX isn't a new programming language, but a technique for building fast, dynamic pages. With it, you can

  • Update content without reloading the page
  • Request data from a server
  • Download data from a server
  • Send data to a server in the background

Definition

AJAX = Asynchronous JavaScript and XML. The name is a bit misleading, because you can use AJAX even if you don't know XML.

Applications

Apps that use AJAX include Google Maps, Gmail, YouTube, Facebook, and more.

How AJAX Works

ajax

AJAX Is Based on Internet Standards

AJAX is based on internet standards, mainly these two

  • XMLHttpRequest object (to retrieve data from a web server)
  • JavaScript/DOM (to display/use the data)

AJAX became popular in 2005 because of Google Suggest. As you type in the search box, JavaScript sends data to the server, and the server returns a list of suggestions based on your input.

XMLHttpRequest object

The XMLHttpRequest object is the foundation of AJAX. All modern browsers support the XMLHttpRequest object, which is used to exchange data with a server.

Create an XMLHttpRequest object
xhr = new XMLHttpRequest();

Sending an AJAX Request

We use the XMLHttpRequest object's open() and send() methods to send a request:

GET

1
2
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

POST

1
2
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

get-post

Add headers

1
2
3
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

setRequestHeader

The definition makes it clear that AJAX is asynchronous, so the third argument to open() is set to true. Asynchronous execution is great news for developers. Server-side work is usually slow, and before AJAX, many operations could cause the page to hang or stop. With AJAX, JavaScript no longer has to keep waiting for the server's response

  • Scripts can keep running while waiting for the server's response
  • The response can be handled as soon as it's ready.
1
2
3
4
5
6
7
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

Server Response

Use the XMLHttpRequest object's responseText (as String) and responseXML (as XML) properties to get the server's response.

responseText

1
2
If the server responds with a string, you can use it directly
document.getElementById("demo").innerHTML = xhttp.responseText;

responseXML

1
2
3
4
5
6
7
8
Request cd_catalog.xml from the server and parse the response
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;

The AJAX onreadystatechange Event

If you look closely, we've already used some events, such as onreadystatechange for when the response is ready. After sending a request, we want to take action based on the server's response. The onreadystatechange event fires every time readyState changes. readyState holds the status of the XMLHttpRequest. The
image below shows some important properties of the XMLHttpRequest object
onreadystatechange
In this image, you can see that the response is ready when readyState is 4 and status is 200. Here's an example in code:

1
2
3
4
5
6
7
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};

AJAX and PHP

This example shows how a web page communicates with the server as you type characters. Here's the source code:

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
<!DOCTYPE html>
<html>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>

PHP file gethint.php

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
47
48
49
50
51
52
53
54
55
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;

##AJAX and Databases
This example shows how a web page uses AJAX to fetch data from a database

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "getcustomer.asp?q="+str, true);
xhttp.send();
}

getcustomer.asp queries the database and returns the information to the HTML page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/datafolder/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn
response.write("<table>")
do until rs.EOF
for each x in rs.Fields
response.write("<tr><td><b>" & x.name & "</b></td>")
response.write("<td>" & x.value & "</td></tr>")
next
rs.MoveNext
loop
response.write("</table>")
%>

Reference: w3schools