
Examples in Ajax
Here are some practical examples of how AJAX can be used in web development, showcasing various functionalities and scenarios:
1. Simple AJAX Request with XMLHttpRequest
This example demonstrates how to use XMLHttpRequest
to send a request to the server and display the response without reloading the page.
HTML:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Example</title></head><body> <h1>AJAX Example</h1> <button onclick="loadData()">Get Data</button> <div id="result"></div> <script> function loadData() { const xhr = new XMLHttpRequest(); xhr.open("GET", "data.txt", true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("result").innerHTML = xhr.responseText; } }; xhr.send(); } </script></body></html>
Explanation:
- When the user clicks the "Get Data" button, an AJAX request is sent to fetch the content from
data.txt
. - The response is displayed in the
div
with theid="result"
.
2. AJAX with fetch()
API
The fetch()
API is modern and simpler than XMLHttpRequest
. This example fetches data asynchronously using fetch()
and updates the page with the response.
HTML:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fetch API Example</title></head><body> <h1>Fetch API Example</h1> <button onclick="loadData()">Get Data</button> <div id="result"></div> <script> function loadData() { fetch("data.json") .then(response => response.json()) .then(data => { document.getElementById("result").innerHTML = `Name: ${data.name}, Age: ${data.age}`; }) .catch(error => console.error('Error:', error)); } </script></body></html>
Explanation:
- The
fetch()
function sends an HTTP request to fetch data from a file (data.json
). - The
then()
method processes the JSON response and updates the webpage with the data.
3. AJAX Form Submission Without Page Reload
In this example, the user submits a form via AJAX, and the page does not reload after submission.
HTML:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Form Example</title></head><body> <h1>AJAX Form Submission</h1> <form id="myForm"> <label for="name">Name: </label> <input type="text" id="name" name="name"><br> <input type="submit" value="Submit"> </form> <div id="result"></div> <script> document.getElementById("myForm").addEventListener("submit", function(event) { event.preventDefault(); const name = document.getElementById("name").value; const xhr = new XMLHttpRequest(); xhr.open("POST", "submit_form.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=" + encodeURIComponent(name)); }); </script></body></html>
Explanation:
- The form is submitted via AJAX. The
submit
event is intercepted by JavaScript, and the request is sent to the server without reloading the page. - The response from
submit_form.php
is displayed in theresult
div.
4. Live Search / Auto-Complete
In this example, AJAX is used to create a live search feature that fetches data based on the user's input and displays matching results in real time.
HTML:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Live Search</title></head><body> <h1>Live Search</h1> <input type="text" id="search" onkeyup="liveSearch()" placeholder="Search..."> <ul id="result"></ul> <script> function liveSearch() { const query = document.getElementById("search").value; if (query.length < 3) { document.getElementById("result").innerHTML = ""; return; } const xhr = new XMLHttpRequest(); xhr.open("GET", `search.php?q=${encodeURIComponent(query)}`, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const results = JSON.parse(xhr.responseText); let output = ""; results.forEach(item => { output += `<li>${item.name}</li>`; }); document.getElementById("result").innerHTML = output; } }; xhr.send(); } </script></body></html>
Explanation:
- As the user types in the search input, an AJAX request is sent to
search.php
with the search query (q
). - The server returns matching results, which are displayed in an unordered list (
ul
).
5. Displaying Real-Time Data (e.g., Stock Price)
In this example, AJAX is used to fetch real-time data (like stock prices) and update the page without a full reload.
HTML:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-Time Stock Price</title></head><body> <h1>Stock Price: <span id="stockPrice">Loading...</span></h1> <script> function fetchStockPrice() { fetch("stock_price.json") .then(response => response.json()) .then(data => { document.getElementById("stockPrice").textContent = `$${data.price}`; }) .catch(error => console.error("Error fetching stock price:", error)); } // Fetch the stock price every 5 seconds setInterval(fetchStockPrice, 5000); </script></body></html>
Explanation:
- The page initially shows "Loading..." in the stock price section.
- Every 5 seconds, an AJAX request is made to
stock_price.json
, and the stock price is updated dynamically on the page.
Conclusion:
These examples demonstrate how AJAX can be used in various scenarios to create dynamic, interactive web pages. Whether it's loading data asynchronously, submitting forms without page reloads, or providing real-time updates, AJAX enhances the overall user experience by making web applications more responsive and efficient.