AJAX Examples
15 April 2025 | Category: JavaScript
Here are some practical AJAX examples to help you understand how to use AJAX in different scenarios. These examples will cover various use cases like sending data, retrieving data, and handling different types of responses.
1. Basic AJAX Request (GET Method)
This is the simplest example of an AJAX request where data is fetched from a server without reloading the page.
Example: Fetching Data from the Server
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basic AJAX Example</title>
</head>
<body>
<h2>Get Server Time Using AJAX</h2>
<button onclick="getServerTime()">Get Time</button>
<p id="result"></p>
<script>
function getServerTime() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "time.php", true); // Requesting the time.php file
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("result").innerText = xhr.responseText;
} else {
document.getElementById("result").innerText = "Error fetching time.";
}
};
xhr.send();
}
</script>
</body>
</html>
time.php
<?php
echo "Current server time: " . date("H:i:s");
?>
Explanation:
- When you click the button, the JavaScript function
getServerTime()
sends an AJAX request to thetime.php
file. - The server responds with the current time, and the result is displayed on the webpage.
2. AJAX with POST Request (Sending Data)
In this example, we’ll send data (like a username) to the server using a POST request.
Example: Sending Username to Server
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX POST Example</title>
</head>
<body>
<h2>Check Username Availability</h2>
<input type="text" id="username" placeholder="Enter Username">
<button onclick="checkUsername()">Check</button>
<p id="result"></p>
<script>
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "check_username.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("result").innerText = xhr.responseText;
} else {
document.getElementById("result").innerText = "Error checking username.";
}
};
xhr.send("username=" + encodeURIComponent(username));
}
</script>
</body>
</html>
check_username.php
<?php
if (isset($_POST['username'])) {
$username = $_POST['username'];
// Simple username check (you can replace it with database query)
$taken_usernames = ['admin', 'user', 'test'];
if (in_array(strtolower($username), $taken_usernames)) {
echo "Username is taken!";
} else {
echo "Username is available!";
}
}
?>
Explanation:
- When the user enters a username and clicks “Check”, the
checkUsername()
function sends a POST request tocheck_username.php
. - The server checks if the username exists (using a simple array in this case) and responds accordingly.
3. AJAX for Live Search
Here’s an example where you can search for items as you type, and the results are updated dynamically without reloading the page.
Example: Live Search for Products
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Search Example</title>
</head>
<body>
<h2>Live Product Search</h2>
<input type="text" id="search" placeholder="Search for products..." onkeyup="liveSearch()">
<div id="results"></div>
<script>
function liveSearch() {
const query = document.getElementById("search").value;
const xhr = new XMLHttpRequest();
xhr.open("GET", "search_products.php?query=" + encodeURIComponent(query), true);
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>
</html>
search_products.php
<?php
$products = ["Apple", "Banana", "Cherry", "Date", "Grapes", "Mango", "Orange"];
$query = isset($_GET['query']) ? $_GET['query'] : '';
if ($query != '') {
$results = array_filter($products, function ($product) use ($query) {
return strpos(strtolower($product), strtolower($query)) !== false;
});
if (count($results) > 0) {
echo "<ul>";
foreach ($results as $result) {
echo "<li>$result</li>";
}
echo "</ul>";
} else {
echo "No products found!";
}
}
?>
Explanation:
- The
liveSearch()
function is called every time the user types something in the search box. - The AJAX request is sent to
search_products.php
, which checks the query against an array of product names. - The matching products are displayed dynamically on the page as the user types.
4. AJAX with JSON Response
This example demonstrates how to work with JSON data in AJAX.
Example: Fetching and Displaying JSON Data
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX JSON Example</title>
</head>
<body>
<h2>Fetch User Data</h2>
<button onclick="getUserData()">Get User Data</button>
<div id="userInfo"></div>
<script>
function getUserData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "user_data.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
const userInfo = `
<p><strong>Name:</strong> ${data.name}</p>
<p><strong>Email:</strong> ${data.email}</p>
`;
document.getElementById("userInfo").innerHTML = userInfo;
}
};
xhr.send();
}
</script>
</body>
</html>
user_data.php
<?php
$user = [
"name" => "John Doe",
"email" => "john@example.com"
];
echo json_encode($user);
?>
Explanation:
- The
getUserData()
function sends aGET
request touser_data.php
. - PHP generates a JSON response with user data.
- JavaScript parses the JSON response and displays the data in the browser.
💡 Additional AJAX Use Cases
- Form Validation: Using AJAX to validate form fields (e.g., email, username) before submission.
- Real-Time Updates: Real-time notifications or updates (e.g., new messages or status updates).
- File Uploads: Sending files via AJAX without reloading the page.
- Chat Applications: Real-time communication using AJAX requests and responses.
🔑 Key Takeaways
- AJAX allows you to send and receive data from a server asynchronously, making your web pages more dynamic.
- It helps update parts of a webpage without reloading the entire page, improving the user experience.
- Use
XMLHttpRequest
for traditional AJAX calls, or you can use the more modern Fetch API.