AJAX and JavaScript: Comprehensive Guide
AJAX and JavaScript: Comprehensive Guide 1
What is AJAX? 2
Key Benefits: 2
How AJAX Works 2
Basic AJAX Implementation 3
1. XMLHttpRequest (XHR) 3
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
1
Basic Example: Fetch Data with XHR 3
2. Fetch API 3
Basic Example: Fetch Data with Fetch API 3
Sending Data with AJAX 4
Example: POST Request with Fetch 4
Detailed Examples 4
Example 1: Dynamically Update a Page with Fetched Data 5
Example 2: Form Submission with AJAX 5
Exercises 6
Exercise 1: Fetch and Display Data 6
Exercise 2: Create a Search Feature 7
Exercise 3: Validate AJAX Errors 7
Multiple-Choice Questions 7
Question 1: 7
Question 2: 7
Question 3: 7
Best Practices for Using AJAX 8
AJAX (Asynchronous JavaScript and XML) allows web pages to update content asynchronously
by communicating with a server without reloading the entire page. This guide explains AJAX
concepts, provides examples, exercises, and quiz questions to help you master AJAX with
JavaScript.
What is AJAX?
● AJAX: A set of web development techniques using JavaScript, XML/JSON, and APIs to
load or send data to/from servers asynchronously.
● Core Concept: Fetch data or send updates to a server without refreshing the page.
Key Benefits:
1. Faster Interactions: Load content dynamically without full reloads.
2. Improved UX: Create seamless and interactive applications.
3. Reduced Bandwidth: Load only the necessary data.
How AJAX Works
1. Request: A client sends an asynchronous request to the server.
2. Response: The server processes the request and sends a response.
3. Update: JavaScript dynamically updates the webpage with the server's response.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
2
Basic AJAX Implementation
AJAX can be implemented using:
1. XMLHttpRequest (XHR) (Traditional way)
2. Fetch API (Modern approach)
1. XMLHttpRequest (XHR)
Basic Example: Fetch Data with XHR
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1",
true);
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.onerror = function () {
console.error("Request failed.");
};
xhr.send();
}
loadData();
Explanation:
● xhr.open(method, url, async): Initializes the request.
● xhr.onload: Called when the request succeeds.
● xhr.send(): Sends the request to the server.
2. Fetch API
The Fetch API provides a more modern and cleaner syntax.
Basic Example: Fetch Data with Fetch API
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
3
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Explanation:
● fetch(url): Sends a request to the URL.
● response.json(): Parses the response body as JSON.
● .then(): Handles successful responses.
● .catch(): Handles errors.
Sending Data with AJAX
Example: POST Request with Fetch
const postData = {
title: "New Post",
body: "This is a new post.",
userId: 1
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Explanation:
● Headers: Specify content type as JSON.
● Body: Send data in JSON format.
Detailed Examples
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
4
Example 1: Dynamically Update a Page with Fetched Data
<!DOCTYPE html>
<html lang="en">
<head>
<title>AJAX Example</title>
</head>
<body>
<div id="content">Loading...</div>
<button id="loadBtn">Load Data</button>
<script>
document.getElementById("loadBtn").addEventListener("click", () =>
{
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => {
document.getElementById("content").textContent = data.title;
})
.catch((error) => console.error("Error:", error));
});
</script>
</body>
</html>
Example 2: Form Submission with AJAX
<!DOCTYPE html>
<html lang="en">
<head>
<title>AJAX Form</title>
</head>
<body>
<form id="myForm">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="Email" required />
<button type="submit">Submit</button>
</form>
<div id="response"></div>
<script>
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
5
document.getElementById("myForm").addEventListener("submit", (e)
=> {
e.preventDefault();
const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, email })
})
.then((response) => response.json())
.then((data) => {
document.getElementById("response").textContent = "Form
submitted successfully!";
})
.catch((error) => console.error("Error:", error));
});
</script>
</body>
</html>
Exercises
Exercise 1: Fetch and Display Data
Fetch user data from https://jsonplaceholder.typicode.com/users and display the
names in a list.
Solution:
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => {
const userList = data.map((user) =>
`<li>${user.name}</li>`).join("");
document.body.innerHTML += `<ul>${userList}</ul>`;
})
.catch((error) => console.error("Error:", error));
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
6
Exercise 2: Create a Search Feature
Create a search box that fetches and displays a post's title based on its ID.
Exercise 3: Validate AJAX Errors
Write a function to handle server errors gracefully when the requested resource does not exist.
Solution:
fetch("https://jsonplaceholder.typicode.com/posts/9999")
.then((response) => {
if (!response.ok) throw new Error("Post not found");
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Multiple-Choice Questions
Question 1:
Which method initializes an XMLHttpRequest?
1. xhr.send()
2. xhr.open()
3. xhr.readyState
4. xhr.get()
Answer: 2. xhr.open()
Question 2:
What does the Fetch API return?
1. A Promise
2. A Callback
3. A JSON Object
4. An XMLHttpRequest Object
Answer: 1. A Promise
Question 3:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
7
Which of the following is NOT true about AJAX?
1. It requires page refreshes for data updates.
2. It works asynchronously.
3. It can fetch data from APIs.
4. It is based on HTTP requests.
Answer: 1. It requires page refreshes for data updates.
Best Practices for Using AJAX
1. Handle Errors Gracefully: Always use .catch() for error handling.
2. Optimize Network Calls: Minimize requests to improve performance.
3. Use Proper Headers: Specify Content-Type for POST requests.
4. Secure Data: Use HTTPS and validate server responses.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis