Ajax Examples in JavaScript
Here are some practical AJAX examples using JavaScript to help you understand how AJAX works in different situations:
? 1. AJAX GET Request (Fetch Text from Server)
<button onclick="loadText()">Load Text</button><div id="output"></div><script>function loadText() { const xhr = new XMLHttpRequest(); xhr.open("GET", "data.txt", true); xhr.onload = function () { if (xhr.status === 200) { document.getElementById("output").innerHTML = xhr.responseText; } }; xhr.send();}</script>Server File (data.txt):
This is a sample response from the server.? 2. AJAX POST Request (Send Form Data to Server)
<form id="myForm"> <input type="text" name="username" placeholder="Username"> <button type="submit">Send</button></form><div id="response"></div><script>document.getElementById("myForm").addEventListener("submit", function(e) { e.preventDefault(); const formData = new FormData(this); fetch("process.php", { method: "POST", body: formData }) .then(res => res.text()) .then(data => { document.getElementById("response").innerHTML = data; });});</script>Server File (process.php):
<?phpecho "Hello, " . $_POST["username"];?>? 3. Live Search with AJAX
<input type="text" id="searchBox" placeholder="Type to search..."><ul id="results"></ul><script>document.getElementById("searchBox").addEventListener("keyup", function () { const query = this.value; fetch("search.php?q=" + encodeURIComponent(query)) .then(res => res.json()) .then(data => { document.getElementById("results").innerHTML = data .map(item => `<li>${item}</li>`) .join(""); });});</script>Server File (search.php) (Example):
<?php$items = ["apple", "banana", "grape", "orange", "pear"];$query = strtolower($_GET["q"]);$results = array_filter($items, fn($item) => strpos($item, $query) !== false);echo json_encode(array_values($results));?>? 4. AJAX Load Data on Button Click
<button onclick="loadUsers()">Load Users</button><div id="userList"></div><script>function loadUsers() { fetch("users.json") .then(res => res.json()) .then(data => { const html = data.map(user => `<p>${user.name} (${user.email})</p>`).join(""); document.getElementById("userList").innerHTML = html; });}</script>Sample users.json:
[ { "name": "Alice", "email": "alice@example.com" }, { "name": "Bob", "email": "bob@example.com" }]? 5. AJAX Error Handling
fetch("nonexistent.php") .then(res => { if (!res.ok) { throw new Error("Network response was not ok"); } return res.text(); }) .then(data => console.log(data)) .catch(error => console.error("There was a problem:", error));Would you like to see one of these examples using Classic ASP or AJAX with JSON data from a database?