AJAX (Asynchronous JavaScript and XML)
AJAX allows web pages to update data asynchronously, which means that only the necessary
parts of the page are updated without the need to reload the entire page. This creates a more
dynamic and interactive user experience, similar to a desktop application. AJAX uses JavaScript,
HTML, and XML to communicate with the server in the background.
Key Concepts of AJAX:
1. Asynchronous: AJAX operations do not require waiting for the server's response before
proceeding with other actions. This makes web applications faster and more efficient.
2. XMLHttpRequest Object: The XMLHttpRequest object is central to AJAX
communication, enabling the sending and receiving of data from the server without
refreshing the page.
3. Server Communication: AJAX interacts with a server-side language (like PHP) to fetch
data. This data can be in various formats, such as XML, JSON, or plain text.
4. No Page Reloading: When implementing AJAX, only specific parts of the web page are
updated, without a full page refresh.
Example 1: Basic AJAX with HTML and JavaScript
In this example, a button click triggers an AJAX call that fetches data from a file ( data.txt) and
displays it on the page without reloading.
<html>
<head>
<title>An Ajax demo</title>
<script language="javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>An Ajax demo</H1>
<form>
<input type="button" value="Fetch the message"
onclick="getData('data.txt', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
In this example:
XMLHttpRequestObject is created based on the browser type.
When the button is clicked, it triggers the getData function, which fetches data from
data.txt and updates the targetDiv element with the response.
The readyState and status are checked to ensure that the data is successfully fetched
before updating the webpage.
Example 2: AJAX with PHP
You can also use AJAX with server-side technologies like PHP. In this example, the
index.html file calls a PHP script (datas.php) to fetch data from the server.
<html>
<head>
<title>AJAX with PHP</title>
<script language="javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<h1>AJAX with PHP</h1>
<form>
<input type="button" value="Fetch the message"
onclick="getData('datas.php', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
PHP Code (datas.php):
<?php
echo "This text was echoed from datas.php with AJAX";
?>
When the button is clicked, the browser sends a request to the datas.php file on the server, and
the result is displayed in the targetDiv without refreshing the page.
Example 3: Passing Data to Server Using GET
In the following example, data is sent to the server using the GET method.
<input type="button" value="Fetch Message 1" onclick="getData('choosem.php?
data=1', 'targetDiv')">
PHP Code (choosem.php):
<?php
if ($_REQUEST["data"] == "1") {
echo "Value sent to the server is 1";
}
if ($_REQUEST["data"] == "2") {
echo "Value sent to the server is 2";
}
?>
In this example:
The value (data=1) is passed in the URL when the button is clicked.
The server-side script (choosem.php) reads this data and sends a response, which is
displayed in the targetDiv.
Example 4: Handling Data with POST Method
The POST method allows for more secure data transmission as the data is not appended to the
URL. Here's how data can be passed to the server using POST in an AJAX request.
<input type="button" value="Fetch Message 1" onclick="getData('choosem.php',
'targetDiv', 1)">
JavaScript (Modified for POST):
function getData(dataSource, divID, data) {
if (XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("POST", dataSource);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-
form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status
== 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("data=" + data);
}
}
In this example:
The POST method is used to send data to the server, which is not visible in the URL.
The server (PHP) processes the data and returns a response.
Example 5: Handling XML Data with AJAX
AJAX can also be used to fetch and process XML data. Here's how it works:
<select id="productsList" onchange="setproducts()">
<option>Select an item</option>
</select>
<input type="button" value="Fetch products" onclick="getProducts()">
JavaScript (AJAX with XML):
function getProducts() {
var XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.open("GET", "products.xml", true);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status ==
200) {
var xmlDoc = XMLHttpRequestObject.responseXML;
var products = xmlDoc.getElementsByTagName("item");
listProducts(products);
}
};
XMLHttpRequestObject.send(null);
}
function listProducts(products) {
var selectControl = document.getElementById('productsList');
for (var i = 0; i < products.length; i++) {
selectControl.options[i] = new Option(products[i].firstChild.data);
}
}
Example 6: Handling XML Data with PHP
In this example, PHP generates XML data dynamically, which is fetched via AJAX.
PHP Code (products.php):
<?php
header("Content-type: text/xml");
if ($_REQUEST["items"] == "1") {
$items = array('PHP Book', 'Television', 'Radio');
} else {
$items = array('Soda', 'Cheese', 'Salami');
}
echo '<?xml version="1.0" ?>';
echo '<items>';
foreach ($items as $item) {
echo '<item>' . $item . '</item>';
}
echo '</items>';
?>
In this case:
PHP returns dynamic XML content based on the query string passed (items=1 or
items=2).
JavaScript processes the returned XML data and displays it.