How the BOM and DOM work together to deliver the Web Application




<body bgcolor="red">

<h1> An HTML page is a topology (connected edged graph of vertices) of NODES </h1>
<h2> These nodes work together to deliver the experience of the Web Page</h2>
<h3> Nodes have : Data and Events </h3>
The BOM Browser Object Model is the Machine Shop at the center
of the factory called a Web page. Bom = the set of objects that represent the browser.

<li> We need to understand how to work with selectors:</li>

<li> These are ways in CSS or JavaScript to select elements in the DOM.</li>

<li> We can select elements by their tag name, class name, id, or any other attribute.</li>
<h2> I am a section</h2>
<p> I am a paragraph</p>
<p> I am another paragraph</p>

<img src="./brown-line-friends.gif"/>



Visualization of POST and GET Protocols

In this lab, you will create a full-stack web application using Node.js for the backend and
HTML, CSS, and JavaScript for the frontend.
The application will feature a quiz on AI application development, testing your knowledge through a series of multiple-choice questions.

What do Get and Post mean?

A HTML form is an HTML coding element that lives in the BOM, on the Client Side.
The Simple Description of a FORM:
A form gives you a set of fields you present to the user. Each field is identified by a NAME.
These fields allow user to input information.
Once user is DONE: They click the SUBMIT BUTTON.
When user clicks on the Submit button: BOM wraps up the form fields with their data and sends them over the SERVER. The server plucks out the data from the fields and delivers your algorithm in processing that data. The mechanism by which the form field data is conveyed from client to server is: Routing End Points.
The ROUTES may by Post or Get: In both cases, the BOM connects to an endpoint on the server program. The server unpacks the req object to retrieve the data and process it.
The FORM lives in the BOM - The Browser Object Model - Listen to Divvy explain the BOM as she talks you through her first Day at Work:

How Post and Get work to convey data from web browser to server program:

Post requests must be generated from a FORM.
Get requests are just generated from the URL Address Bar.

Visualization of POST and GET Protocols

John (GET Protocol) and
Suzan (POST Protocol)
Scene: AI Application Development Quiz Lab
**John and Suzan, the two protocols, are sitting in a cozy, well-lit lab room filled with computers and coding books.
They are discussing their roles in the AI Application Development Quiz Lab.**
**John (GET Protocol)**:
"Hey Suzan, have you seen how smooth my job is in this lab? I just grab data from the server whenever the user needs it. It's straightforward and quick!"
**Suzan (POST Protocol)**: "Oh really, John? I'd argue that my job is way more important.
I handle all the data submissions from the users. Without me, there would be no way to submit the answers to the quiz!"
**John (GET Protocol)**: "Sure, Suzan, but all I need to do is get the questions from the server. The browser's address bar handles everything for me.
Look, when a user starts the quiz, they send a GET request to `/quiz` to fetch the questions. It’s as simple as typing a URL!"

Suzan (POST Protocol)**: "I see your point, John. GET requests are indeed simple and visible in the URL.
But think about the complexity I manage. When the user submits their answer, I have to collect the data from the form and send it securely to the server via a POST request.
My data isn't visible in the URL, making it more secure for sensitive information."

**John (GET Protocol)**: "Okay, you have a point about security. But don't forget, I have to ensure the server knows which question to send back.
The users send URL-encoded parameters, and I have to parse them correctly. Like this: `http://localhost:3000/user/YourName`. The server then uses `` to get the name."
**Suzan (POST Protocol)**: "True, but while you handle simple key-value pairs in the URL, I manage more complex data in the body of the request.
When users submit their answers, the form data goes through me. I use `req.body` to access the submitted answers.
Plus, I ensure that the server receives the data in a structured way."

**John (GET Protocol)**: "Alright, Suzan. Let's break it down for the students. When they load the quiz page, here’s what happens:
They hit the GET endpoint to fetch the quiz questions. This is where I come in. I fetch the data and bring it back to the browser to display the questions."
Suzan (POST Protocol): "Exactly, John. And after the user selects an answer and clicks 'Submit,' it's my turn.
I take the selected answer and send it to the server using a POST request to `/check-answer`. The server then checks if the answer is correct and responds back to the browser, which updates the user on their performance."
**John (GET Protocol)**: "It's a team effort, Suzan. The GET protocol makes fetching data quick and easy, visible right in the URL. It's perfect for retrieving data that doesn't change the state of the server."

Suzan (POST Protocol)**: "And the POST protocol ensures that data submission is secure and can handle larger, more complex data. It's essential for operations that modify server state, like submitting quiz answers."
**John (GET Protocol)**: "So, whose job is harder?"
**Suzan (POST Protocol)**: "I think both our jobs are equally challenging in different ways. You deal with the simplicity and visibility of URLs, while I handle the security and complexity of data submission."
**John (GET Protocol)**: "Agreed. Together, we make the AI Application Development Quiz Lab run smoothly. Without either of us, the application wouldn't function properly."
**Summary for Students:**
- GET Protocol (John): - Used for retrieving data from the server. - Parameters are visible in the URL. - Simple key-value pairs are encoded in the URL. - Ideal for fetching data without changing server state.
- POST Protocol (Suzan): - Used for submitting data to the server. - Data is sent in the body of the request, not visible in the URL. - Can handle larger, more complex data. - Essential for operations that modify server state.
Together, John and Suzan show how GET and POST requests work in harmony to create a functional, secure, and user-friendly web application in the AI Application Development Quiz Lab.

key Learning Outcomes:
- Understand the use of GET and POST routes in a Node.js server.
- Develop skills in creating interactive web applications.
- Learn to handle form submissions and process data on both client and server sides.
- Gain experience in designing user-friendly interfaces with HTML and CSS.
- Enhance your JavaScript skills by implementing dynamic quiz functionality.
Let's get started with building our Quiz Generator and explore the integration of backend and frontend technologies via ROUTES, post and get.

Program Requirements and Deliverables for the Lab

Objective: The purpose of this lab is to create a web application that demonstrates the use of GET and POST routes in a Node.js backend server.
The application will present a quiz on AI application development, allowing users to select answers and receive feedback on their correctness.
The application will also tabulate and display the user's score after answering multiple questions.


1. **Backend Server (Node.js)**: - Create a Node.js server using Express. - Set up routes to handle GET and POST requests. - **GET Route**: Serve quiz data (questions and answers) as a JSON object. - **POST Route**: Accept user answers, compare them to the correct answers, and return a response indicating whether the answer is correct.

2. Data Structure:

- Store the quiz questions and answers in a JSON format within the backend code. - Ensure questions are themed on AI application development.

3. Frontend Interface (HTML, CSS, JavaScript):

- Develop an HTML page to display the quiz.
- Use CSS to style the quiz interface, making it visually appealing.
- Create a form to display questions and multiple-choice answers.
- Use JavaScript to:
- Fetch quiz data from the backend data store (an array in the Server program).
- Display questions and answer options.
- Handle form submissions to check answers.
- Loop through five questions and keep track of the user's score.
- Display the user's final score after completing the quiz.

4. Functional Flow: - On page load, fetch the quiz data from the server using a GET request. - Display one question at a time with multiple-choice options. - On answer submission, send the selected answer to the server using a POST request to check its correctness.
- Display feedback on whether the answer is correct or incorrect.
- Move to the next question and repeat the process until all five questions are answered.
- Finally, display the user's total score.


SERVER means: Node.js program (running on your own laptop)
Client means: The BOM - living in the HTML Browser running the Web Page.
1. Backend Code (server.js): - Node.js server with the required routes and middleware. - JSON structure for quiz questions and answers.
2. Frontend Files: - `index.html`: HTML file containing the quiz interface. - `style.css`: CSS file for styling the quiz interface. - `script.js`: JavaScript file to handle frontend logic, including fetching data, displaying questions, handling submissions, and updating the score.
3. Deployment and Testing: - Instructions for setting up and running the Node.js server. - Steps to access and interact with the quiz through a web browser.
Lab Introduction:
Welcome to the AI Application Development Quiz Lab! In this lab, you will create a full-stack web application using Node.js for the backend and HTML, CSS, and JavaScript for the frontend. The application will feature a quiz on AI application development, testing your knowledge through a series of multiple-choice questions.
Key Learning Outcomes: - Understand the use of GET and POST routes in a Node.js server. - Develop skills in creating interactive web applications. - Learn to handle form submissions and process data on both client and server sides. - Gain experience in designing user-friendly interfaces with HTML and CSS. - Enhance your JavaScript skills by implementing dynamic quiz functionality.
Let's get started with building our AI Application Development Quiz and explore the integration of backend and frontend technologies!

How static middleware works:

Here’s how you can create an application that meets your requirements.

Backend: Node.js Server (server.js)
1. **Create `server.js`
const express = require('express'); const app = express(); const port = 3000; const path = require('path');
// Middleware to parse URL-encoded bodies and JSON app.use(express.urlencoded({ extended: true })); app.use(express.json());
// Serve static files app.use(express.static('public'));
// Sample questions and answers const quizData = [ { question: "What is the primary language used for AI application development?", options: ["JavaScript", "Python", "Ruby", "Java"], answer: "Python" }, { question: "Which of the following is a popular library for deep learning?", options: ["TensorFlow", "React", "Django", "Flask"], answer: "TensorFlow" }, { question: "What does NLP stand for in AI?", options: ["Natural Language Processing", "Neural Learning Program", "Network Learning Protocol", "None of the above"], answer: "Natural Language Processing" }, { question: "Which algorithm is commonly used for classification problems?", options: ["K-Means", "Decision Tree", "Apriori", "Breadth-First Search"], answer: "Decision Tree" }, { question: "What is the purpose of reinforcement learning?", options: ["To learn from labeled data", "To learn from unlabeled data", "To learn through rewards and punishments", "To optimize a function"], answer: "To learn through rewards and punishments" } ];
// Route to get quiz data app.get('/quiz', (req, res) => { res.json(quizData); });
// Route to check answer'/check-answer', (req, res) => { const { questionIndex, selectedAnswer } = req.body; const correctAnswer = quizData[questionIndex].answer; const isCorrect = selectedAnswer === correctAnswer; res.json({ isCorrect }); });
// Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });

Frontend: HTML, CSS, and JavaScript

2. **Create the folder structure**: - `public` - `index.html` - `style.css` - `script.js`
3. Create `index.html`:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Quiz</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>AI Application Development Quiz</h1> <div id="quiz-container"> <p id="question"></p> <div id="options"></div> <button id="submit" onclick="submitAnswer()">Submit</button> </div> <div id="score-container"> <p id="score"></p> </div> </div> <script src="script.js"></script> </body> </html>
4. **Create `style.css`**:
```css body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
.container { max-width: 600px; margin: 50px auto; padding: 20px; background-color: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); border-radius: 8px; }
h1 { text-align: center; color: #333; }
#quiz-container { display: none; }
#score-container { display: none; text-align: center; }
button { display: block; width: 100%; padding: 10px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; margin-top: 10px; }
button:hover { background-color: #218838; }
5. Create `script.js`:
let currentQuestionIndex = 0; let score = 0; let quizData = [];
document.addEventListener("DOMContentLoaded", () => { fetchQuizData(); });
function fetchQuizData() { fetch('/quiz') .then(response => response.json()) .then(data => { quizData = data; displayQuestion(); }); }
function displayQuestion() { if (currentQuestionIndex < quizData.length) { const questionData = quizData[currentQuestionIndex]; document.getElementById('question').innerText = questionData.question; const optionsDiv = document.getElementById('options'); optionsDiv.innerHTML = ''; questionData.options.forEach(option => { const optionElement = document.createElement('div'); optionElement.classList.add('option'); optionElement.innerHTML = ` <input type="radio" name="option" value="${option}" id="${option}"> <label for="${option}">${option}</label> `; optionsDiv.appendChild(optionElement); }); document.getElementById('quiz-container').style.display = 'block'; document.getElementById('score-container').style.display = 'none'; } else { displayScore(); } }
function submitAnswer() { const selectedOption = document.querySelector('input[name="option"]:checked'); if (selectedOption) { const selectedAnswer = selectedOption.value; fetch('/check-answer', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ questionIndex: currentQuestionIndex, selectedAnswer: selectedAnswer }) }) .then(response => response.json()) .then(data => { if (data.isCorrect) { score++; } currentQuestionIndex++; displayQuestion(); }); } else { alert('Please select an option!'); } }
function displayScore() { document.getElementById('quiz-container').style.display = 'none'; document.getElementById('score').innerText = `Your score: ${score} out of ${quizData.length}`; document.getElementById('score-container').style.display = 'block'; }


- **Backend (server.js)**: The server provides the quiz data via a GET request and checks the answers via a POST request. - **Frontend (index.html)**: The HTML structure includes a form for displaying questions and a button for submitting answers. - **CSS (style.css)**: Basic styling to make the front end look decorative. - **JavaScript (script.js)**: Fetches quiz data, displays questions, checks answers, and updates the score.

To run the application:

1. Ensure you have Node.js installed. 2. Save the provided code into respective files. 3. Navigate to the directory in the terminal and run `npm init -y` to create a `package.json` file. 4. Install Express by running `npm install express`. 5. Start the server by running `nodemon server.js`. 6. Open your browser and navigate to `http://localhost:3000` to see the quiz application in action.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.