0% found this document useful (0 votes)
6 views1 page

app.js

The document is a JavaScript code snippet that manages a student list on a webpage. It fetches student data from a backend API and displays it, allowing users to add new students through a form. Upon submission, the new student is sent to the server, and the list is refreshed to include the new entry.

Uploaded by

iamtahereditz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

app.js

The document is a JavaScript code snippet that manages a student list on a webpage. It fetches student data from a backend API and displays it, allowing users to add new students through a form. Upon submission, the new student is sent to the server, and the list is refreshed to include the new entry.

Uploaded by

iamtahereditz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// app.

js
document.addEventListener('DOMContentLoaded', () => {
const studentList = document.getElementById('student-list');
const addStudentForm = document.getElementById('add-student-form');

// Fetch all students from the backend


function fetchStudents() {
fetch('http://localhost:3000/api/students')
.then(response => response.json())
.then(data => {
studentList.innerHTML = '';
data.forEach(student => {
const li = document.createElement('li');
li.textContent = `${student.name} (${student.email})`;
studentList.appendChild(li);
});
})
.catch(err => console.error('Error fetching students:', err));
}

// Add a new student


addStudentForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;

fetch('http://localhost:3000/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email })
})
.then(response => response.json())
.then(() => {
fetchStudents(); // Refresh the list of students
})
.catch(err => console.error('Error adding student:', err));
});

fetchStudents(); // Initial fetch of students


});

You might also like