AJAX and JSON in JavaScript_ Comprehensive Guide
AJAX and JSON in JavaScript_ Comprehensive Guide
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
1
Basic AJAX with JSON 3
Example: Fetch JSON Data with XMLHttpRequest 3
Modern AJAX with Fetch API 3
Example: Fetch Data and Display JSON 4
Sending Data with AJAX 4
Example: POST JSON Data Using Fetch 4
Detailed Examples 5
Example 1: Display Posts in a List 5
Example 2: Search Users with a Form 5
Exercises 6
Exercise 1: Fetch and Display Data 6
Solution: 6
Exercise 2: Submit Form Data 6
Solution: 6
Exercise 3: Handle Errors Gracefully 7
Multiple-Choice Questions 7
Question 1: 7
Question 2: 7
Question 3: 8
Best Practices for AJAX and JSON 8
AJAX (Asynchronous JavaScript and XML) and JSON (JavaScript Object Notation) are core
technologies for creating dynamic web applications. This guide explains how to use AJAX to
interact with servers and how JSON is used to handle data, with detailed examples, exercises,
and quiz questions.
What is AJAX?
AJAX enables web pages to communicate with servers asynchronously, meaning the page
doesn't reload or refresh while sending or receiving data.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format for structuring and exchanging
data. It is commonly used with AJAX for server responses and requests.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
2
Example JSON:
{
"name": "Alice",
"age": 25,
"skills": ["JavaScript", "React", "Node.js"],
"isEmployed": true
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
3
Example: Fetch Data and Display JSON
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json(); // Parse JSON
})
.then((data) => {
console.log(data); // JSON object
})
.catch((error) => {
console.error("Error:", error);
});
4
Detailed Examples
5
});
</script>
Exercises
Solution:
fetch("https://jsonplaceholder.typicode.com/comments")
.then((response) => response.json())
.then((comments) => {
const container = document.getElementById("comments");
comments.forEach((comment) => {
const commentDiv = document.createElement("div");
commentDiv.innerHTML =
`<strong>${comment.name}</strong><p>${comment.body}</p>`;
container.appendChild(commentDiv);
});
});
Create a form with fields for title and body. When the form is submitted, send the data as a
JSON object to https://jsonplaceholder.typicode.com/posts.
Solution:
<form id="postForm">
<input type="text" id="title" placeholder="Title" required />
<textarea id="body" placeholder="Body" required></textarea>
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script>
document.getElementById("postForm").addEventListener("submit", (e)
=> {
e.preventDefault();
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
6
const title = document.getElementById("title").value;
const body = document.getElementById("body").value;
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body }),
})
.then((response) => response.json())
.then((data) => {
document.getElementById("result").textContent = `Post created
with ID: ${data.id}`;
})
.catch((error) => console.error("Error:", error));
});
</script>
Modify any of the above examples to handle errors more robustly. Display a user-friendly
message if the request fails.
Multiple-Choice Questions
Question 1:
1. JSON.stringify()
2. JSON.parse()
3. JSON.convert()
4. JSON.objectify()
Answer: 2. JSON.parse()
Question 2:
1. A JSON object.
2. An XMLHttpRequest object.
3. A Promise.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
7
4. A callback.
Answer: 3. A Promise.
Question 3:
1. Content-Length
2. Accept
3. Content-Type: application/json
4. Authorization
1. Validate Input: Ensure data sent to the server is sanitized and validated.
2. Handle Errors: Use .catch() or try-catch to manage errors gracefully.
3. Use Async/Await: Simplify promise chains for better readability.
4. Test APIs: Test API endpoints using tools like Postman or cURL.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis