AJAX
AJAX
Introduction:
AJAX (Asynchronous JavaScript and XML) is a web development technique that enables
web pages to send and receive data from a server asynchronously—without reloading the entire
page. Originally introduced by Microsoft in 1999 through the XMLHttpRequest object in
Internet Explorer 5, it allowed dynamic content updates in the background. The term "AJAX"
was popularized in 2005 by Jesse James Garrett, describing a combination of HTML, CSS,
JavaScript, and XML (now mostly replaced by JSON) to create faster, interactive web
applications. Today, AJAX forms the backbone of modern web interactivity and is widely used
in frameworks and APIs like Fetch, Axios, and jQuery.
What is Ajax?
2. CSS (Cascading Style Sheets) – Provides the styling and layout of the web
application.
1|Page
4. XML (Extensible Markup Language) – Originally used to store and transport
data from the web server. (Note: Today, JSON is more commonly used due to its
simplicity and compatibility with JavaScript.)
Asynchronous means that the the Web Application could send and receive data from the Web
Server without refreshing the page. This background process of sending and receiving data
from the server along with updating different sections of a web page defines Asynchronous
property/feature of AJAX.
1. Reduced Page Load Time: By updating only parts of the page instead of reloading the
entire page, Ajax significantly reduces the load time.
2. Enhanced User Experience: Users can continue interacting with the web page while
data is being fetched or sent, leading to a smoother experience.
3. Efficient Data Transmission: Ajax requests typically send and receive smaller
amounts of data compared to full page reloads, making interactions faster and reducing
server load.
AJAX enables dynamic communication between a web page and a web server without
refreshing the whole page. The process follows these core steps:
1. User Interaction
➤ A user performs an action on the webpage (e.g., clicks a button or submits a form).
➤ JavaScript captures the event and uses the browser's built-in XMLHttpRequest
object to send an asynchronous request to the server.
3. Server-Side Processing
2|Page
➤ The web server receives the request, processes it, and sends back a response. The
response is usually in JSON, XML, or HTML format.
4. DOM Update
➤ JavaScript receives the response and updates the relevant part of the webpage using
the HTML DOM (Document Object Model)—without reloading the entire page.
XMLHttpRequest Object
➤ A JavaScript API used to send and receive data asynchronously between the
web browser and the server. It provides methods like .open() and .send() to make
HTTP requests.
HTML DOM
3|Page
Programming in AJAX
Javascript:
This object allows JavaScript to communicate with the server without reloading the entire web
page.
Value Meaning
0 Request not initialized
1 Server connection established
2 Request received
3 Processing request
4|Page
Commonly Used Methods of XMLHttpRequest :
To send a request to the server, use the following methods:
1. open(method, url, async) – Prepares the request.
This method sets up the request before it is sent using send(). It does not actually
send the request — it just prepares it.
method (String):
Specifies the HTTP method used to make the request.
Common methods include:
o "GET" – Requests data from the server (data is sent in the URL).
o "POST" – Sends data to the server (used for submitting form data).
o "PUT" – Updates data on the server.
o "DELETE" – Deletes data from the server.
url (String):
o Defines the location of the server resource (a file or API endpoint) that
will handle the request.
o It can be a local file ("file.txt") or a server endpoint ("server.php" or
"https://example.com/api").
async (Boolean):
o Determines whether the request is sent asynchronously (true) or
synchronously (false).
o true (default): The script continues to run while the request is being
processed. Recommended for non-blocking operations.
o false: The script waits (blocks) until the request is completed before
continuing. Rarely used today due to UI freezing.
2. send() – Sends the request to the server.
Purpose: Sends the request to the server after open() is called.
Use:
o send() with no argument for GET requests.
o send(data) with data (like form input) for POST requests.
Example:
Javascript:
xhttp.open("GET", "data.php", true);
xhttp.send();
5|Page
Before using the open() and send() methods in AJAX, we must first check the status of
the request using the onreadystatechange property of the XMLHttpRequest object. This
function is called automatically whenever the readyState of the request changes. Inside it, we
check if readyState == 4 (which means the request is complete) and status == 200 (which means
the request was successful). Only when both conditions are true, we write our logic — usually
to update the webpage with the response from the server. After setting this up, we use the
open(method, url, async) method to prepare the request and the send() method to send it to the
backend server (like a PHP file).
Example:
Javascript:
function fetchData() {
request.onreadystatechange = function() {
document.getElementById("output").innerHTML = this.responseText;
};
request.open("GET", "yourfile.php", true); // You can also use "POST" and a different URL
request.send();
6|Page
Example:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>AJAX with PHP Example</title>
</head>
<body>
<div id="foo">
<h2>Click the Button to Load Content from PHP</h2>
<button type="button" onclick="changeContent()">Change Content</button>
</div>
<script>
function changeContent() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Update the page with the response
document.getElementById("foo").innerHTML = this.responseText;
}
};
// Asynchronous GET request to the PHP file
xhttp.open("GET", "data.php", true);
xhttp.send();
}
</script>
</body>
</html>
7|Page
data.php:
<?php
echo "<h2>This content was loaded from a PHP file using AJAX!</h2>";
?>
8|Page
1. Fetch API – Simpler syntax, Promise-based, and more powerful.
2. Axios (Library) – Easy to use, supports promises, interceptors, and more.
Advantages of Using AJAX in Programming
1. No Page Reload
o AJAX sends and receives data without refreshing the whole page.
2. Faster Updates
o Only parts of the page are updated, so it works quickly.
3. Smooth Experience
o Users can keep using the page while data loads in the background.
4. Less Server Work
o It sends only needed data, saving server time and internet data.
5. Live Content Updates
o Useful for updating things like chat messages or search results without
reloading.
6. Works Everywhere
o Uses common web tech like HTML, CSS, and JavaScript, and works with any
backend like PHP, Python, etc.
7. Connects to Server Easily
o Can fetch or send data from various server files or APIs.
8. Good for Real-Time Apps
o Perfect for apps that need to update often, like weather or stock sites.
9. Faster Communication
o Less waiting time because only small data is exchanged.
10. Flexible for Developers
o Developers can control how data is sent, received, and shown on the page.
9|Page