Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I handle form submissions using JavaScript without reloading the page?
Asked on Mar 12, 2026
Answer
To handle form submissions without reloading the page, you can use JavaScript to intercept the form's submit event and then use the Fetch API to send the form data asynchronously.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<input type="text" name="username" placeholder="Enter your username" required>
<input type="email" name="email" placeholder="Enter your email" required>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission
const formData = new FormData(this);
fetch('/submit-form', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "event.preventDefault()" method prevents the default form submission, allowing you to handle it with JavaScript.
- "FormData" is used to construct a set of key/value pairs representing form fields and their values, which can be sent using the Fetch API.
- The Fetch API is used to send the form data to the server asynchronously, without reloading the page.
- The ".then()" method handles the response, and ".catch()" handles any errors that occur during the fetch operation.
Recommended Links:
