-
Hajipur, Bihar, 844101
AJAX stands for Asynchronous JavaScript and XML. It is not a programming language, but a technique that allows web pages to communicate with the server without reloading the entire page.
With AJAX, you can request data from the server, receive a response, and update parts of a web page dynamically. This improves user experience by making web applications faster, smoother, and more interactive.
AJAX uses a combination of:
JavaScript – To send requests and handle responses asynchronously.
XMLHttpRequest (XHR) object – Core of AJAX for communicating with the server.
HTML/CSS – To display content on the page.
Server-side scripts (PHP, Node.js, etc.) – To process requests and return data, usually in XML, JSON, or plain text.
The basic workflow:
A user triggers an event (like clicking a button).
JavaScript creates an XMLHttpRequest object.
The request is sent to the server asynchronously.
The server processes the request and sends a response.
JavaScript receives the response and updates the web page dynamically.
Here’s a simple example to demonstrate how AJAX works:
HTML File: index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Intro Example</title>
<script>
function fetchMessage() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "message.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</head>
<body>
<h2>AJAX Demo</h2>
<button onclick="fetchMessage()">Get Message</button>
<div id="result" style="margin-top:20px;"></div>
</body>
</html>
PHP File: message.php
<?php
echo "Hello! This message was fetched using AJAX.";
?>
The XMLHttpRequest object handles the AJAX request.
xhr.open("GET", "message.php", true) sets the request method and URL.
xhr.onreadystatechange monitors changes in the request state.
When readyState is 4 (request finished) and status is 200 (success), the response is displayed in the div with id="result".
Clicking the button fetches the message without reloading the page.
The readyState property of XMLHttpRequest shows the current state of the request:
| Value | State |
|---|---|
| 0 | Request not initialized |
| 1 | Server connection established |
| 2 | Request received |
| 3 | Processing request |
| 4 | Request finished and response ready |
Faster user experience – Only part of the page updates, not the entire page.
Reduced server load – Smaller requests compared to full page reloads.
Dynamic content – Pages can respond instantly to user actions.
Smooth interactions – Makes web apps behave more like desktop applications.
Live search suggestions
Form validation without page reload
Loading new content dynamically (e.g., news feeds, comments)
Real-time notifications
Polls and surveys
Updating tables or dashboards dynamically
AJAX supports GET and POST methods:
GET: Requests data from the server. Parameters are appended to the URL. Best for fetching data.
POST: Sends data to the server securely in the request body. Best for submitting forms.
Example using POST:
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send("name=Sunita&age=25");
Although AJAX originally used XML, modern applications often use JSON because it’s easier to work with in JavaScript.
PHP (data.php)
<?php
$data = array("name" => "Sunita", "age" => 25, "course" => "Web Development");
echo json_encode($data);
?>
JavaScript
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML =
"Name: " + obj.name + ", Age: " + obj.age + ", Course: " + obj.course;
}
};
xhr.send();
JSON allows you to send structured data efficiently and access it easily in JavaScript.
It’s important to handle errors:
xhr.onerror = function() {
alert("Request failed. Please try again.");
};
You can also check xhr.status to handle server errors (like 404 or 500).
AJAX is a powerful technique that allows web pages to interact with servers dynamically without reloading.
Key points:
AJAX uses JavaScript and XMLHttpRequest to communicate asynchronously.
It improves speed, user experience, and interactivity.
Data can be returned in text, XML, or JSON format.
It’s widely used for live search, dynamic content, form validation, and real-time updates.
GET and POST methods determine how data is sent or received.
Understanding AJAX is the foundation for building modern, responsive web applications.
Create a simple HTML page with a button that fetches a message from a PHP file using AJAX and displays it in a div.
Modify the previous example to fetch the current server time instead of a static message.
Create a form with a single input field. Use AJAX to send the input value to a PHP file and return a greeting message.
Create an HTML page with two buttons: one that fetches data using GET and another using POST. Display the responses in separate div elements.
Write a PHP file that returns a JSON object with a user’s name, age, and course. Use AJAX to fetch this data and display it dynamically.
Create a page that uses AJAX to fetch a random quote from a PHP file every 5 seconds without reloading the page.
Implement error handling in an AJAX request. Display an alert if the request fails.
Create a dropdown menu with three options. Use AJAX to send the selected option to the server and display a relevant message.
Modify the message-fetching example to show a “Loading…” text while waiting for the server response.
Create a small page that uses AJAX to fetch content from different PHP files dynamically when clicking multiple buttons (e.g., “About”, “Contact”, “Services”).