Explain the steps involved in AJAX coding with an example that fetches and displays data from a server without reloading the page.
AJAX (Asynchronous JavaScript and XML) allows you to fetch data from a server asynchronously without having to reload the entire webpage. Below, I'll explain the steps involved in AJAX coding and provide a simple example that fetches and displays data from a server.
### Steps Involved in AJAX Coding
1. **Set Up Your HTML**: Create the basic HTML structure where the AJAX request will be initiated and where the response data will be displayed.
2. **Create an XMLHttpRequest Object**: This object is used to send the AJAX request.
3. **Define the Callback Function**: This function will be called when the server responds. It typically processes the response data and updates the web page.
4. **Open a Connection**: Use the `open()` method to configure the request with the HTTP method (GET/POST) and the URL to request data from.
5. **Send the Request**: Invoke the `send()` method to send the request to the server.
6. **Handle the Response**: Within the callback function, check if the request is successful (HTTP status 200). If successful, manipulate the DOM (Document Object Model) to display the data.
7. **Error Handling**: Implement error handling in case the request fails.
### Example
Let's create an example that fetches a list of users from a mock API and displays it on the web page.
#### HTML Code
```html
<!DOCTYPE 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>Fetch User Data</h1>
<button id="fetch-users">Fetch Users</button>
<ul id="user-list"></ul>
<script src="app.js"></script>
</body>
</html>
```
#### JavaScript Code (`app.js`)
```javascript
document.getElementById('fetch-users').addEventListener('click', function() {
// Step 2: Create an XMLHttpRequest Object
const xhr = new XMLHttpRequest();
// Step 3: Define the Callback Function
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // Request is complete
if (xhr.status === 200) { // Successful response
const users = JSON.parse(xhr.responseText); // Parse JSON string to object
displayUsers(users); // Call function to display data
} else {
console.error('Error fetching data: ' + xhr.status);
}
}
};
// Step 4: Open a Connection
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true);
// Step 5: Send the Request
xhr.send();
});
// Function to display users on the web page
function displayUsers(users) {
const userList = document.getElementById('user-list');
userList.innerHTML = ''; // Clear existing entries
users.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.name} - ${user.email}`;
userList.appendChild(li);
});
}
```
### Explanation of the Code
1. **HTML Structure**: A button to trigger the AJAX request and an unordered list to display user data.
2. **JavaScript Code**:
- An event listener is added to the button that triggers the AJAX request when clicked.
- An `XMLHttpRequest` object is created to facilitate the request.
- The `onreadystatechange` event handler checks if the request is complete (`readyState === 4`) and whether it was successful (`status === 200`).
- If successful, the JSON response is parsed, and `displayUsers` is called to update the HTML with user data.
- The `open()` method initializes a GET request to a sample API, and `send()` sends the request to the server.
- The `displayUsers` function iterates over the parsed user data and dynamically creates list elements in the unordered list to display user names and emails.
### Conclusion
This example demonstrates how to use AJAX to fetch data from a server and display it on a webpage without reloading it. Adjust the URL or modify the data accordingly to fit your application needs.