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

Student Registration Form Submission

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)
10 views6 pages

Student Registration Form Submission

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

//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="[Link]">
</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="[Link]" class="link">View Registered Students</a>
</div>
</div>
</div>

<script src="[Link]"></script>
</body>
</html>




[Link]​

const studentForm = [Link]("studentForm");

[Link]("submit",async (e)=>{
[Link]();

const name = [Link]("name").value;


const email = [Link]("email").value;
const college = [Link]("college").value;
const description = [Link]("description").value;

[Link]("Form data:", {name,email,college,description});

try {

const reqestBody = [Link]({name,email,college,description});


[Link]("request body",reqestBody);

const response = await


fetch("[Link]
method: "POST",
headers:{
"Content-Type": "application/json",
},
body: requestBody
});

[Link]("api response", response);

if([Link]){
alert("Student Added Successfully");
[Link]();
}else{
alert('issue')
}
} catch (error) {
[Link]("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 = [Link]("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​

[Link]("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 [Link]()?​

[Link]();

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

3. Collect the Input Values​

const name = [Link]("name").value;
const email = [Link]("email").value;
const college = [Link]("college").value;
const description = [Link]("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.

[Link] the Data
[Link]("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 = [Link]({ 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": "john@[Link]",
"college": "XYZ University",
"description": "A passionate learner."
}

6. Send the Data to the Server​



const response = await fetch("[Link] {
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:
"[Link]
○​ 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 ([Link]) {
alert("Student Added Successfully");
[Link]();
} else {
alert("Issue");
}

What does this do?

●​ [Link] checks if the server says the request was successful.


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

8. Handle Errors​

catch (error) {
[Link]("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 ([Link]()).
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: "john@[Link]"
○​ College: "XYZ University"
○​ Description: "A student passionate about learning."
2.​ Click "Register."
3.​ The data is sent to [Link]
4.​ If successful:
○​ "Student Added Successfully" is displayed.
○​ The form is cleared.

Common questions

Powered by AI

After a successful data submission, the code uses studentForm.reset() to clear all form fields . This process is important to prepare the form for new data entry, improving usability by providing visual feedback that the current data has been successfully processed and the form is ready for the next input .

The steps to prepare and send student registration data include: collecting input values from the form fields (name, email, college, description), transforming this data into a JSON string using JSON.stringify, and then using the fetch() API to send a POST request to the specified server endpoint with this JSON data as the body .

Once 'Register' is clicked, the following steps occur sequentially: the 'submit' event is intercepted, preventing page reload (e.preventDefault), input values are collected, the data is serialized into JSON, a POST request is sent to the server, the server response is evaluated for success or error, and user feedback is provided through alerts, with form reset if successful .

Expected errors during submission include network issues or server accessibility problems. The code uses try-catch blocks to handle such errors. In the catch block, errors are logged to the console, allowing developers to debug the issue without disturbing the user experience .

The code transforms form input data by gathering values into a JavaScript object and then converting this object into a JSON string using JSON.stringify. This transformation is necessary for compatibility with server communication protocols, which expect data in a standard format like JSON for consistent interpretation and processing .

Including 'Content-Type: application/json' in the headers is vital because it informs the server that the request body contains JSON data. The server needs this information to correctly parse and understand the incoming data format, ensuring proper handling and storage of the data .

The JavaScript code uses e.preventDefault() in the form's 'submit' event to prevent the default action of reloading the page upon form submission . This is necessary to allow the data to be handled with custom logic, enabling the collection and processing of the form data without interaction disruptions caused by page reloads .

The event listener is crucial for capturing the form's 'submit' event, allowing developers to inject custom logic during form submission. This ability enables dynamic interactions without page reloads, such as data validation, transformation, and asynchronous data submission to servers, thereby enhancing user experience and application performance .

The JavaScript code checks the server's response using response.ok to determine if the submission was successful. If true, an alert stating 'Student Added Successfully' is shown, and the form is reset. If not, an alert with 'Issue' is presented to the user . This gives immediate feedback on the outcome of the submission .

Logging error messages in the console is a significant debugging practice as it allows developers to capture and analyze runtime issues without exposing them to end-users. This approach preserves the user interface while providing insight into potential execution problems, assisting in swift identification and resolution of issues .

You might also like