0% found this document useful (0 votes)
3 views6 pages

Js API Integration

The document contains an HTML form for student registration, including fields for name, email, college, and description, along with a JavaScript file that handles form submission. Upon submission, the data is collected, converted to JSON, and sent to an API endpoint to save the student's details. The script also manages success and error responses from the API, providing user feedback accordingly.

Uploaded by

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

Js API Integration

The document contains an HTML form for student registration, including fields for name, email, college, and description, along with a JavaScript file that handles form submission. Upon submission, the data is collected, converted to JSON, and sent to an API endpoint to save the student's details. The script also manages success and error responses from the API, providing user feedback accordingly.

Uploaded by

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

//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 Registration</title>
<link rel="stylesheet" href="student.css">
</head>
<body>
<header>
<h1>Register a Student</h1>
</header>
<div class="container">
<div class="form-container">
<h2>Fill the Details</h2>
<form id="studentForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Enter student name"
required />
</div>

<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Enter student
email" required />
</div>

<div class="form-group">
<label for="college">College</label>
<input type="text" id="college" name="college" placeholder="Enter college
name" required />
</div>

<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" rows="4" placeholder="Enter
a short description" required></textarea>
</div>

<button type="submit" class="btn">Register</button>


</form>
<div class="nav-link">
<a href="students.html" class="link">View Registered Students</a>
</div>
</div>
</div>

<script src="register.js"></script>
</body>
</html>




register.js​

const studentForm = document.getElementById("studentForm");

studentForm.addEventListener("submit",async (e)=>{
e.preventDefault();

const name = document.getElementById("name").value;


const email = document.getElementById("email").value;
const college = document.getElementById("college").value;
const description = document.getElementById("description").value;

console.log("Form data:", {name,email,college,description});

try {

const reqestBody = JSON.stringify({name,email,college,description});


console.log("request body",reqestBody);

const response = await


fetch("https://crudapp-m2nk.onrender.com/api/products",{
method: "POST",
headers:{
"Content-Type": "application/json",
},
body: requestBody
});

console.log("api response", response);

if(response.ok){
alert("Student Added Successfully");
studentForm.reset();
}else{
alert('issue')
}
} catch (error) {
console.error("error",error);
}
})





This JavaScript code handles the form submission for adding a new student. When you fill
out the form and click "Submit," it sends the data (name, email, college, description) to an
API to save the student's details.​


1. Get the Form​

const studentForm = document.getElementById("studentForm");

This selects the <form> element with the id="studentForm" from your HTML.
Now, studentForm represents your form, and you can use it to handle what happens when
the form is submitted.

2. Add an Event Listener​

studentForm.addEventListener("submit", async (e) => { ... });

What is this doing?

●​ It listens for the "submit" event on the form. This event happens when you click the
"Register" button.
●​ When the form is submitted, the code inside the function runs

Why e.preventDefault()?​

e.preventDefault();

By default, when you submit a form, the page reloads. We use e.preventDefault() to
stop that from happening so we can handle the data ourselves.​

3. Collect the Input Values​

const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
const college = document.getElementById("college").value;
const description = document.getElementById("description").value;

These lines grab the values you entered into the form fields (name, email, college, and
description).
The .value gives the text or input you typed in.

4.Log the Data
console.log("Form data:", { name, email, college, description });

This just prints the collected form data (name, email, college, description) in the browser
console so you can see it.​

5. Prepare the API Request​

const reqestBody = JSON.stringify({ name, email, college, description });

What is this?

●​ The form data is turned into a JSON string. This format is required when sending
data to the server.


Example:​
{
"name": "John Doe",
"email": "[email protected]",
"college": "XYZ University",
"description": "A passionate learner."
}

6. Send the Data to the Server​



const response = await fetch("https://crudapp-m2nk.onrender.com/api/products", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: requestBody,
});

What is this doing?


●​ It uses the fetch API to send the data to the server.
1.​ URL:
○​ The API endpoint:
"https://crudapp-m2nk.onrender.com/api/products".
○​ This is where the data is sent.
2.​ Method:
○​ "POST" is used because you are adding new data (a student).
3.​ Headers:
○​ Content-Type: application/json tells the server you're sending JSON
data.
4.​ Body:
○​ reqestBody is the JSON string with the form data.

7. Check the Server’s Response​



if (response.ok) {
alert("Student Added Successfully");
studentForm.reset();
} else {
alert("Issue");
}

What does this do?

●​ response.ok checks if the server says the request was successful.


●​ If successful:
○​ Show a success message: alert("Student Added Successfully").
○​ Reset the form using studentForm.reset() to clear all fields.
●​ If something went wrong:
○​ Show an error message: alert("Issue")

8. Handle Errors​

catch (error) {
console.error("error", error);
}

Why?

●​ If something goes wrong (e.g., no internet, server down), this catch block runs.
●​ It prints the error in the console so you can debug it.


What Happens When You Submit the Form?

1.​ The form is submitted, but the page doesn’t reload (e.preventDefault()).
2.​ It collects the data you entered in the form fields.
3.​ Converts the data into JSON format.
4.​ Sends the data to the API endpoint using a POST request.
5.​ Checks if the server successfully saved the data:
○​ Shows a success message if everything worked.
○​ Otherwise, shows an error message.
6.​ If there’s a network or other error, it logs the error in the console


Example Flow

1.​ You fill out the form like this:


○​ Name: "John Doe"
○​ Email: "[email protected]"
○​ College: "XYZ University"
○​ Description: "A student passionate about learning."
2.​ Click "Register."
3.​ The data is sent to https://crudapp-m2nk.onrender.com/api/products.
4.​ If successful:
○​ "Student Added Successfully" is displayed.
○​ The form is cleared.

You might also like