In the current web development environment, creating a smooth user experience is essential. Ever notice how websites accept form submissions without causing any interruptions to your browsing? It's all thanks to JavaScript. Before, in the traditional submission techniques; the page frequently reloads or reroutes to another page after submission. The procedure causes data entered to be lost, which interferes with the user experience and might cause dissatisfaction. Imagine carefully completing a long form, only to have all of your information vanish with only a click of the submit button. This issue may make users less engaged with the form or even deter them from completing it at all.
In this article, we'll explore the fundamentals of form submission techniques using JavaScript. Regardless of your level of coding knowledge, take on us as we explore how to improve your online forms for a more polished user experience.
In web development, it's common to need to display HTML form data on the same page after submission, particularly when making interactive and user-friendly interfaces. To implement this functionality, one usually has to use JavaScript to collect form input and then dynamically update the Document Object Model (DOM) with the values that are provided.
Syntax:
Syntax for form submitting form using JavaScript:
function submitForm() {
var formData = new FormData(document.getElementById('exampleForm'));
fetch('submit.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
}
- First, you define a function named
'submitForm()'
to handle form submission.
- You create a FormData object named formData to capture form data.
- Use Fetch API to send a 'POST' request to
'submit.php'
with form data.
- You use chains. It is used to handle server response.
- It extracts response body as text and logs it to the console.
- It catches errors and logs them to the console.
- It follows that form submissions are handled by a server-side script called submit.php.
- Without refreshing the page, it permits asynchronous form submission.
- It improves the user experience by managing submission in the background.
Displaying HTML Form Values on the Same Page After Submission
Interactive and user-friendly interfaces are created by displaying HTML form data on the same page after submission. The following steps will be involved in the process of submitting form on same page:
- Create HTML Form: The HTML code creates a form with input fields for name and email, along with a submit button.
- Attach Event Listener: The JavaScript code attaches an event listener to the form submission event.
- Capture Form Values: Inside the event listener, JavaScript captures the values entered by the user in the form fields.
- Update Page Content: After capturing the values, JavaScript updates the page content to display the submitted values dynamically on the same page.
Step 1: Create HTML Form
First, You will create an HTML form with the necessary input fields. Each input field should have a unique id attribute for easy access via JavaScript. The code is as followed:
<form id="exampleForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
Step 2: Attach Event Listener
Use JavaScript to add an event listener to the form submission event. This enables you to handle the form submission programmatically by intercepting it. The code is as followed:
document.getElementById('exampleForm').addEventListener('submit', function(event) {
// Prevent the default form submission behaviour
event.preventDefault();
// Your code to handle form submission goes here
});
Validate form input to enhance user experience.
Step 3: Capture Form Values
Inside the event listener, you capture the values entered by the user in the form fields. You can access form elements using their id attributes and retrieve their values.
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
Step 4: Update Page Content
Use JavaScript to dynamically update the page content with the submitted values. This typically involves selecting a target element on the page and modifying its inner HTML to display the form values.
document.getElementById('displayValues').innerHTML = '<h2>Submitted Values</h2>' +
'<p>Name: ' + name + '</p>' +
'<p>Email: ' + email + '</p>';
Here, 'displayValues' is the id of the element where you want to display the submitted values.
Step 5: Capture Form Values
Compile all of the above procedures into a single JavaScript code block that receives form submissions, records form values, and modifies the page's content as necessary.
document.getElementById('exampleForm').addEventListener('submit', function(event) {
event.preventDefault();
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
document.getElementById('displayValues').innerHTML = '<h2>Submitted Values</h2>' +
'<p>Name: ' + name + '</p>' +
'<p>Email: ' + email + '</p>';
});
Output:
Some Alternative Approaches
In addition, you may use the following methods to submit form on same page:
1. Using JSON Serialization
It involves serialising form data by hand into a JSON object. In this procedure, the form components are iterated over in order to create a JavaScript object, where field names are represented by keys and field values by values. The input values are then shown on the same page using HTML that is dynamically produced.
<body>
<h2>Example Form</h2>
<form id="exampleForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
<div id="displayValues"></div>
<script>
document.getElementById('exampleForm').addEventListener('submit', function(event) {
event.preventDefault();
// Serialize form data to JSON
var formData = {};
var formElements = this.elements;
for (var i = 0; i < formElements.length; i++) {
var element = formElements[i];
if (element.name) {
formData[element.name] = element.value;
}
}
// Display values on the same page
var displayHTML = '<h2>Submitted Values</h2>';
for (var key in formData) {
displayHTML += '<p>' + key + ': ' + formData[key] + '</p>';
}
document.getElementById('displayValues').innerHTML = displayHTML;
});
</script>
</body>
- In this approach, we manually serialize the form data into a JSON object.
- Upon submission of the form, we stop the default behaviour using
'event.preventDefault()'
.
- We iterate over the form elements and construct a JavaScript object (formData) where keys are the field names and values are the field values.
- Finally, we dynamically generate HTML to display the submitted values on the same page.
2. Using jQuery
This method simplifies event handling and DOM manipulation by using the jQuery framework. Form data serialisation is made simpler by jQuery's 'serializeArray()'
function, which turns form data into an array of objects. After that, HTML is dynamically generated using this serialised data to show the provided information.
<head>
<title>Display Form Values</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Example Form</h2>
<form id="exampleForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
<div id="displayValues"></div>
<script>
$(document).ready(function() {
$('#exampleForm').submit(function(event) {
event.preventDefault();
// Serialize form data
var formData = $(this).serializeArray();
// Display values on the same page
var displayHTML = '<h2>Submitted Values</h2>';
$.each(formData, function(index, field) {
displayHTML += '<p>' + field.name + ': ' + field.value + '</p>';
});
$('#displayValues').html(displayHTML);
});
});
</script>
</body>
Q: Can I use the same approach for more complex forms with multiple pages?
A: Yes, you can extend this approach for multi-page forms by dynamically loading content or using a single-page application (SPA) framework.
References
Here are the official reference links for the concepts and methods used in the provided approaches: