0% found this document useful (0 votes)
19 views7 pages

NodeJS CRUD

The document outlines the creation of a webpage for managing student information with CRUD actions, including a form for inputting student details and a table for displaying the student list. It provides HTML structure, JavaScript functions for fetching, displaying, adding, editing, and deleting student records, as well as pagination controls. The webpage interacts with a local API at 'http://localhost:3001' to perform these operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views7 pages

NodeJS CRUD

The document outlines the creation of a webpage for managing student information with CRUD actions, including a form for inputting student details and a table for displaying the student list. It provides HTML structure, JavaScript functions for fetching, displaying, adding, editing, and deleting student records, as well as pagination controls. The webpage interacts with a local API at 'http://localhost:3001' to perform these operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Goal: building a webpage including CRUD actions

Configs:
 Student information: _id, studentId, name, dob, address
 const apiUrl = 'http://localhost:3001'

Steps:

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<title>Student CRUD</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<script src="./script.js"></script>
</body>
</html>

Form to input student information (index.html)


<!-- Modal Popup for Student Form -->
<div id="studentModal" class="modal">
<div class="modal-content">
<span class="close" id="closeModal">&times;</span>
<form id="studentForm">
<input type="hidden" id="dbEntryId" />
<label for="studentId">Student ID:</label>
<input type="number" id="studentId" />
<label for="name">Name:</label>
<input type="text" id="name" required />
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" required />
<label for="address">Address:</label>
<input type="text" id="address" required />
<button type="submit" id="addSubmit">Add Student</button>
<button type="submit" id="editSubmit">Edit Student</button>
</form>
</div>
</div>

A table to show student list (index.html)


<div class="container">
<h1>Student Information</h1>
<button id="addStudentBtn">Add Student</button>

<table id="studentTable">
<thead>
<tr>
<th style="display: none">Database Entry Id</th>
<th>Student ID</th>
<th>Name</th>
<th>Date of Birth</th>
<th>Address</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="studentList">
<!-- Rows will be dynamically added here -->
</tbody>
</table>
<div id="paginationControls" class="pagination-controls"></div>
</div>

Get student and add to the table


// Fetch and display students in a table
async function fetchStudents() {
const response = await fetch(apiUrl);
students = (await response.json()).data;
displayStudents()
setupPagination()
}

function displayStudents() {
const studentTableBody = document.getElementById('studentList');
studentTableBody.innerHTML = ''; // Clear existing data

const start = (currentPage - 1) * pageSize


const end = start + pageSize

const paginatedStudents = students.slice(start, end)

paginatedStudents.forEach(student => {
const tr = document.createElement('tr');

tr.innerHTML = `
<td style="display: none">${student._id}</td>
<td>${student.studentId}</td>
<td>${student.name}</td>
<td>${student.dob.slice(0, 10)}</td>
<td>${student.address}</td>
<td>
<button class="edit" onclick="loadStudent('$
{student._id}')">Edit</button>
<button class="delete" onclick="deleteStudent('$
{student._id}')">Delete</button>
</td>
`;
studentTableBody.appendChild(tr);
});
}

Pagination
// Setup pagination controls
function setupPagination() {
const paginationControls =
document.getElementById('paginationControls');
paginationControls.innerHTML = ''; // Clear existing pagination buttons
const totalPages = Math.ceil(students.length / pageSize);

for (let i = 1; i <= totalPages; i++) {


const button = document.createElement('button');
button.textContent = i;
button.classList.add('pagination-btn');
if (i === currentPage) {
button.classList.add('active'); // Highlight the current page
}

button.addEventListener('click', () => {
currentPage = i;
displayStudents(); // Display the students for the selected
page
});

paginationControls.appendChild(button);
}
}
// Add or update student
document.getElementById('studentForm').addEventListener('submit', async
(event) => {
event.preventDefault();

console.log(document.getElementById('update'))
const isUpdate = event.submitter.id != "addSubmit"
const method = isUpdate ? 'PUT' : 'POST'
let url = apiUrl

const studentData = {
dbEntryId: document.getElementById('dbEntryId').value,
studentId: document.getElementById('studentId').value,
name: document.getElementById('name').value,
dob: document.getElementById('dob').value,
address: document.getElementById('address').value
};

if (method === 'PUT') {


url += `/${studentData.dbEntryId}`
}

try {
const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(studentData)
});

if (response.ok) {
hidePopup(); // Hide the popup after saving
await fetchStudents();
} else {
const errorResponse = await response.json();
alert("Error: ", errorResponse)
}
} catch (error) {
console.error('Error adding/updating student: ', error)
}
});

// Load student data into the form for editing


async function loadStudent(id) {
const response = await fetch(`${apiUrl}/${id}`);
const student = (await response.json()).data;
document.getElementById('dbEntryId').value = student._id;
document.getElementById('studentId').value = student.studentId;
document.getElementById('name').value = student.name;
document.getElementById('dob').value = student.dob.slice(0, 10);
document.getElementById('address').value = student.address;
showPopup(true); // Show the form in popup when editing

// Show the "Create Student" popup form


function showPopup(isUpdate) {
const popup = document.getElementById('studentModal');
popup.style.display = 'block';
if (isUpdate) {
popup.querySelector("#editSubmit").style.display = 'block'
} else {
popup.querySelector("#addSubmit").style.display = 'block'
}
}

// Hide the "Create Student" popup form


function hidePopup() {
const popup = document.getElementById('studentModal');
popup.style.display = 'none';
popup.querySelector("#addSubmit").style.display = 'none'
popup.querySelector("#editSubmit").style.display = 'none'
document.getElementById('studentForm').reset();
}

// Event listener for the "Add Student" button to show the popup
document.getElementById('addStudentBtn').addEventListener('click', () => {
showPopup(false) });

// Event listener to close the modal


document.getElementById('closeModal').addEventListener('click', hidePopup)

// Delete student
async function deleteStudent(id) {
await fetch(`${apiUrl}/${id}`, { method: 'DELETE' });
await fetchStudents();
}
// Initial fetch of students
fetchStudents();

/* Modal Styling */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
form#studentForm button[type="submit"] {
display: none;
}

- Class container:
.container {
width: 95%;
margin: auto;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ddd;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy