AJAX and JavaScript_ Comprehensive Guide
AJAX and JavaScript_ Comprehensive Guide
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:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
2
Basic AJAX Implementation
1. XMLHttpRequest (XHR)
Explanation:
2. Fetch API
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:
Explanation:
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>
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
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.
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:
1. xhr.send()
2. xhr.open()
3. xhr.readyState
4. xhr.get()
Answer: 2. xhr.open()
Question 2:
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?
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis