DOM + Fetch API – public/script.js - 9.6 | Chapter 9: Project – Student Feedback Web App | Full Stack Web Development Basics
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Understanding DOM Manipulation

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we’re going to discuss the Document Object Model, or DOM, which allows us to interact with HTML elements. Can anyone tell me what the DOM is?

Student 1
Student 1

Is it like a structure of our HTML document?

Teacher
Teacher

Exactly! The DOM represents the structure of the document as a tree of objects. That's why we can easily manipulate it with JavaScript. Remember the acronym 'C.R.U.D' – it stands for Create, Read, Update, and Delete, which are the basic operations we can perform on DOM elements.

Student 2
Student 2

Can you give an example of how we use it in our project?

Teacher
Teacher

Sure! In our feedback app, we use the DOM to add new feedback to the list dynamically. After we submit the form, we create a new list item in the feedback section. Anyone know how to create a new element in JavaScript?

Student 3
Student 3

You use `document.createElement`!

Teacher
Teacher

Correct! So, we use `document.createElement('li')` to create a new list item for each feedback. Let’s summarize: the DOM allows us to dynamically interact with our web page structure.

The Fetch API

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Next, let’s talk about the Fetch API. What do you think it does?

Student 4
Student 4

Isn't it used for making HTTP requests?

Teacher
Teacher

Exactly! It allows us to fetch data from a server or send data to a server. In our project, we use it to send feedback and retrieve existing data from our server. Just remember the phrase 'F for Fetch, F for Future data' to recall its purpose!

Student 1
Student 1

How do we use Fetch in our code?

Teacher
Teacher

Great question! We call `fetch(url)` where 'url' is our endpoint. For example, `fetch('/feedbacks')` retrieves existing feedback. You then handle the response as JSON. Can anyone tell me how we handle errors with Fetch?

Student 2
Student 2

We can use `.catch()` to handle errors, right?

Teacher
Teacher

Correct! Always remember to handle errors gracefully. So, Fetch allows us to communicate seamlessly with our server – another takeaway is to integrate your error handling!

Handling Form Submission

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now, let's discuss how we handle form submissions in our app. What happens when a user submits their feedback?

Student 3
Student 3

We prevent the default behavior and create a feedback object!

Teacher
Teacher

Exactly! We use `e.preventDefault()` to stop the form from reloading the page. This way, we can gather the input values into an object. It's crucial to remember with a simple acronym 'N.M.S' – Name, Message, Timestamp; these are the key pieces of data we collect.

Student 4
Student 4

And after we have that data, we send it to the server with Fetch!

Teacher
Teacher

Right! We send it using a POST request to `/submit-feedback` and include our feedback data as the body of the request. What does it return after submission?

Student 1
Student 1

An alert shows the success message, and we update the UI!

Teacher
Teacher

Exactly! You all are grasping this very well. Let's quickly recap the steps: Capture input, prevent default, structure data, send it, handle response.

Dynamic UI Updates

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Lastly, let's see how we can update our user interface dynamically. What is the benefit of updating the feedback list without re-fetching data?

Student 2
Student 2

It makes the application feel faster and more responsive!

Teacher
Teacher

Absolutely! After a successful submission, we append the new feedback to the current list. Can anyone tell me how we do that?

Student 3
Student 3

We call the `addFeedbackToUI` function with the new feedback data.

Teacher
Teacher

Perfect! This function creates an item in the feedback list and displays it without reloading the page. Just remember to use the phrase 'Add Immediately, Save Time' so you can recall the purpose of this approach.

Student 1
Student 1

I like that! It really helps me remember the method.

Teacher
Teacher

Great! By minimizing reloads, we enhance user experience. Let's summarize: Dynamic updates keep the app snappy and user-friendly.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section focuses on implementing the DOM manipulation and Fetch API to submit and display feedback in a web app.

Standard

In this section, we cover how to use JavaScript to interact with the Document Object Model (DOM) for a feedback form by capturing user input and sending it to the server using the Fetch API. Additionally, we ensure existing feedback is fetched and displayed upon loading the app.

Detailed

Summary of Section 9.6: DOM + Fetch API

In this section, we explore how to implement dynamic behavior in our student feedback web application through JavaScript's DOM manipulation and Fetch API. The main tasks implemented include:

  1. Event Listener for DOM Content Loaded: We start by ensuring that our JavaScript code runs after the HTML document is fully loaded, thus guaranteeing that elements are accessible.
  2. Fetching Existing Feedback: We use the Fetch API to retrieve and display feedback from the server. A GET request is sent to the endpoint /feedbacks, which reads data from feedback.json and dynamically adds each feedback to the application's user interface using a function that creates list items.
  3. Form Submission Handling: When the user submits the feedback form, we prevent the default form submission behavior using e.preventDefault(). Then, we create an object containing the feedback details (name, message, and time) and send this data to the server using a POST request to /submit-feedback.
  4. Updating the UI: Upon successfully submitting feedback, the response is shown to the user via an alert, and the form resets. The newly submitted feedback is immediately appended to the feedback list without re-fetching, providing instant feedback.

This integration of DOM manipulation with the Fetch API enables a responsive portal for students to give feedback effectively, contributing significantly to the functionality of the web app.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

DOM Content Loaded Event

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

document.addEventListener('DOMContentLoaded', () => {

Detailed Explanation

The line of code listens for the 'DOMContentLoaded' event, which signifies that the initial HTML document has been completely loaded and parsed, including all dependent resources like stylesheets and images. This ensures that the JavaScript only runs after the initial page structure is available in the browser's DOM.

Examples & Analogies

Think of it like waiting for a cake to cool down before you can frost it. You can't frost a cake while it's still baking; similarly, this code waits until the page is fully loaded before executing the script.

Selecting Form Elements

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

const form = document.getElementById('feedbackForm');
const nameInput = document.getElementById('name');
const messageInput = document.getElementById('message');
const feedbackList = document.getElementById('feedbackList');

Detailed Explanation

This part of the code retrieves references to various elements from the HTML document using their IDs. The 'form' variable points to the entire feedback form, while 'nameInput' and 'messageInput' refer to input fields for the user's name and feedback message, respectively. 'feedbackList' is for displaying the submitted feedback on the page.

Examples & Analogies

Imagine being in a classroom where you need to gather items. You locate your backpack (form), your pencil (nameInput), your notebook (messageInput), and your checklist (feedbackList) to keep track of everything you have.

Fetching Existing Feedback

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

fetch('/feedbacks')
.then(res => res.json())
.then(data => {
data.forEach(fb => addFeedbackToUI(fb));
});

Detailed Explanation

This code snippet uses the Fetch API to send a GET request to the '/feedbacks' endpoint. When the server responds, the response is converted to JSON format. The data, which is an array of feedback objects, is then iterated over, and each feedback is passed to the function 'addFeedbackToUI' to be displayed on the web page.

Examples & Analogies

Picture yourself checking your mailbox for letters. When you open it and see several letters (feedback), you read each one (convert to JSON) and place them on your desk (UI) for easy access.

Form Submission Handling

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

form.addEventListener('submit', (e) => {
e.preventDefault();
const feedback = {
name: nameInput.value,
message: messageInput.value,
time: new Date().toLocaleString()
};

Detailed Explanation

This event listener detects when the feedback form is submitted. The 'e.preventDefault()' method stops the form from submitting in the traditional sense, which would refresh the page. Instead, it collects the input values and creates an object representing the feedback that includes the name, message, and current time.

Examples & Analogies

Imagine you are about to shout out your answer in class (submitting the form), but you pause (preventDefault) to gather your thoughts before sharing (collecting input values).

Sending Feedback to the Server

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

fetch('/submit-feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(feedback)
})

Detailed Explanation

Here, another fetch request is made, but this time it is a POST request to the '/submit-feedback' endpoint. The 'Content-Type' header specifies that the body of the request contains JSON data. The feedback object is converted to a JSON string and sent to the server.

Examples & Analogies

Think of it like sending a letter (POST request) through the mail. You carefully write down your message (feedback), seal it in an envelope (JSON.stringify), and hand it over to the post office (server) for delivery.

Handling Server Response

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

.then(res => res.json())
.then(data => {
alert(data.message);
addFeedbackToUI(feedback);
form.reset();
});

Detailed Explanation

After sending the feedback, the code waits for the server's response. Once the response is received, it is processed as JSON. An alert displays a message sent back from the server, the newly submitted feedback is added to the UI using the same 'addFeedbackToUI' function, and the form fields are cleared for further input.

Examples & Analogies

Imagine you've just submitted an application (sending feedback) and the company responds back with the acceptance message (alert). You feel relieved and immediately start filling out another application (resetting the form) for future projects.

Updating the UI with New Feedback

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

function addFeedbackToUI(fb) {
const li = document.createElement('li');
li.textContent = ${fb.name} (${fb.time}): ${fb.message};
feedbackList.appendChild(li);
}

Detailed Explanation

This function takes a feedback object as input and creates a new list item (

  • ) element. The text content of this list item is set to show the name of the person who submitted the feedback, the time it was submitted, and the message itself. Finally, the new list item is appended to the 'feedbackList' to display it on the web page.
  • Examples & Analogies

    It's like putting a gold star sticker on a wall chart each time a student completes an assignment. Each sticker (feedback) represents a unique achievement (submitted feedback) that gets displayed for everyone to see.

    Definitions & Key Concepts

    Learn essential terms and foundational ideas that form the basis of the topic.

    Key Concepts

    • DOM Manipulation: The process of changing the structure and appearance of HTML elements dynamically using JavaScript.

    • Fetch API: A modern JavaScript API for making HTTP requests to send and retrieve data from a server.

    • Preventing Default: A method in JavaScript to stop the default action of an event from occurring.

    • Dynamic Updates: The technique of refreshing the user interface in real-time without requiring a page reload.

    Examples & Real-Life Applications

    See how the concepts apply in real-world scenarios to understand their practical implications.

    Examples

    • Using document.createElement('li') to create a new list item in the feedback section on form submission.

    • Sending feedback data as a JSON object in a POST request using the Fetch API to the server.

    Memory Aids

    Use mnemonics, acronyms, or visual cues to help remember key information more easily.

    🎵 Rhymes Time

    • Fetch the data, send it right; get the feedback, day or night!

    📖 Fascinating Stories

    • Imagine a teacher gathering notes from students’ feedback every day to make changes. This teacher uses magic to fetch all the notes at once, allowing them to bring joy and improvement faster.

    🧠 Other Memory Gems

    • Remember 'C.R.U.D' for DOM operations: Create, Read, Update, Delete!

    🎯 Super Acronyms

    F for Fetch, F for Future data; when we use Fetch, we're bringing data into our future workflows.

    Flash Cards

    Review key concepts with flashcards.

    Glossary of Terms

    Review the Definitions for terms.

    • Term: DOM (Document Object Model)

      Definition:

      A programming interface that represents the structure of a web document, allowing JavaScript to manipulate HTML elements dynamically.

    • Term: Fetch API

      Definition:

      A JavaScript interface for making HTTP requests to servers, enabling asynchronous data retrieval and sending.

    • Term: Event Listener

      Definition:

      A procedure in JavaScript that waits for events to occur, such as user inputs on elements.

    • Term: Asynchronous

      Definition:

      A programming paradigm that allows operations to occur without blocking the execution of other code.

    • Term: POST Request

      Definition:

      An HTTP request method used to send data to the server, typically used for submitting forms.