Asynchronous JavaScript and XML (AJAX)
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML. It is a technique used to create dynamic web pages by exchanging small amounts of data with the server in the background. This allows for partial page updates without reloading the entire page, enhancing user experience.
Working Principle
AJAX introduces a middle layer between the user and the server, enabling asynchronous operations. Instead of submitting all user requests to the server, some data validation and processing are done locally by the AJAX engine. Only when necessary, the AJAX engine makes requests to the server, fetching new data as needed.
Creating the XMLHttpRequest Object
The XMLHttpRequest
object is fundamental for AJAX operations. Here’s how to create an instance:
var request = new XMLHttpRequest();
Request Sends a Request to the Server
To exchange data with the server, use the open()
and send()
methods of the XMLHttpRequest
object:
-
open(method, url, async)
method
: Type of the request (e.g.,GET
,POST
).url
: Location of the file on the server.async
:true
for asynchronous requests,false
for synchronous.
-
send(string)
string
: Data to send with the request (only applicable forPOST
requests).
Example:
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
Server Response
To handle the server response, use the onreadystatechange
event:
- onreadystatechange: Stores a function to be called whenever the
readyState
changes. - readyState: Represents the current state of the request, ranging from 0 to 4.
- 0: Request uninitialized
- 1: Server connection established
- 2: Request received
- 3: Processing request
- 4: Request completed, response is ready
Example:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
AJAX ASP / PHP Examples
Below is an example where typing a character in an input box triggers a request to the server:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function showHint(str) {
var xmlhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "/try/ajax/gethint.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Enter a letter in the box:</h3>
<form>
Input Name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Prompt: <span id="txtHint"></span></p>
</body>
</html>
PHP File (gethint.php
):
<?php
$a = array("Anna", "Brittany", "Cinderella", "Diana", "Eva", "Fiona", "Gunda", "Hege", "Inga", "Johanna", "Kitty", "Linda", "Nina", "Ophelia", "Petunia", "Amanda", "Raquel", "Cindy", "Doris", "Eve", "Evita", "Sunniva", "Tove", "Unni", "Violet", "Liza", "Elizabeth", "Ellen", "Wenche", "Vicky");
$q = $_GET["q"];
$hint = "";
if (strlen($q) > 0) {
foreach ($a as $value) {
if (strtolower(substr($value, 0, strlen($q))) == strtolower($q)) {
if ($hint === "") {
$hint = $value;
} else {
$hint .= ", " . $value;
}
}
}
}
if ($hint === "") {
$response = "no suggestion";
} else {
$response = $hint;
}
echo $response;
?>
AJAX Database Instance: Show Customer Information
Here’s another example that fetches customer information based on a selection:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function showCustomer(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "/try/ajax/getcustomer.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="customers" onchange="showCustomer(this.value)" style="font-family: Verdana, Arial, Helvetica, sans-serif;">
<option value="APPLE">Apple Computer, Inc.</option>
<option value="BAIDU">BAIDU, Inc</option>
<option value="Canon">Canon USA, Inc.</option>
<option value="Google">Google, Inc.</option>
<option value="Nokia">Nokia Corporation</option>
<option value="SONY">Sony Corporation of America</option>
</select>
</form>
<div id="txtHint">Customer information will be displayed here...</div>
</body>
</html>
PHP File (getcustomer.php
):
<%
Response.expires = -1
sql = "SELECT * FROM CUSTOMERS WHERE CUSTOMERID = '" & Request.QueryString("q") & "'"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Provider = "Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.MapPath("/db/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><td>" & x.Value & "</td></tr>")
Next
rs.MoveNext
Loop
Response.Write("</table>")
%>
These examples illustrate how AJAX can be effectively used to create dynamic web applications.