0% found this document useful (0 votes)
23 views8 pages

AJAX and JSON in JavaScript_ Comprehensive Guide

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views8 pages

AJAX and JSON in JavaScript_ Comprehensive Guide

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

AJAX and JSON in JavaScript: Comprehensive Guide

AJAX and JSON in JavaScript: Comprehensive Guide 1


What is AJAX? 2
Key Features of AJAX: 2
What is JSON? 2
Example JSON: 3
How AJAX and JSON Work Together 3

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.

Key Features of AJAX:

1. Sends and receives data asynchronously.


2. Improves user experience by avoiding full-page reloads.
3. Works with JSON, XML, or plain text as data formats.

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
}

How AJAX and JSON Work Together

1. AJAX Request: A request is sent to the server using JavaScript.


2. Server Response: The server processes the request and sends back a JSON
response.
3. Update Webpage: The client-side script parses the JSON and updates the webpage
dynamically.

Basic AJAX with JSON

Example: Fetch JSON Data with XMLHttpRequest


function fetchData() {
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); // Parse JSON
console.log(data); // { id: 1, title: ..., body: ..., userId: 1
}
}
};
xhr.onerror = function () {
console.error("An error occurred during the request.");
};
xhr.send();
}
fetchData();

Modern AJAX with Fetch API

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);
});

Sending Data with AJAX

Example: POST JSON Data Using 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), // Convert JavaScript object to JSON
string
})
.then((response) => response.json())
.then((data) => {
console.log("Response:", data); // Server response
})
.catch((error) => {
console.error("Error:", error);
});
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

4
Detailed Examples

Example 1: Display Posts in a List


<div id="posts"></div>
<script>
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((posts) => {
const postsContainer = document.getElementById("posts");
posts.forEach((post) => {
const postElement = document.createElement("div");
postElement.innerHTML =
`<h3>${post.title}</h3><p>${post.body}</p>`;
postsContainer.appendChild(postElement);
});
})
.catch((error) => console.error("Error:", error));
</script>

Example 2: Search Users with a Form


<form id="searchForm">
<input type="text" id="userId" placeholder="Enter User ID" />
<button type="submit">Search</button>
</form>
<div id="userDetails"></div>
<script>
document.getElementById("searchForm").addEventListener("submit", (e)
=> {
e.preventDefault();
const userId = document.getElementById("userId").value;
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then((response) => response.json())
.then((user) => {
const userDetails = document.getElementById("userDetails");
userDetails.innerHTML =
`<h3>${user.name}</h3><p>${user.email}</p>`;
})
.catch((error) => console.error("Error:", error));
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

5
});
</script>

Exercises

Exercise 1: Fetch and Display Data

Fetch and display a list of comments from


https://jsonplaceholder.typicode.com/comments. Display the name and body of
each comment.

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);
});
});

Exercise 2: Submit Form Data

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>

Exercise 3: Handle Errors Gracefully

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:

Which method is used to parse JSON data in JavaScript?

1. JSON.stringify()
2. JSON.parse()
3. JSON.convert()
4. JSON.objectify()

Answer: 2. JSON.parse()

Question 2:

What does the fetch function return?

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:

Which header is required for sending JSON data in a POST request?

1. Content-Length
2. Accept
3. Content-Type: application/json
4. Authorization

Answer: 3. Content-Type: application/json

Best Practices for AJAX and JSON

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

You might also like