Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to stop refreshing the page on submit in JavaScript?
In this tutorial, we will learn how to prevent forms from refreshing the page when submitted in JavaScript. By default, form submission causes a page refresh, but there are several methods to override this behavior.
Using event.preventDefault() to Stop Page Refresh
The event.preventDefault() method is the most common and recommended way to prevent the default form submission behavior.
Syntax
form.addEventListener('submit', function(event) {
event.preventDefault();
// Your custom form handling code here
});
Example
In this example, we create a simple contact form that prevents page refresh and shows a success message instead:
<html>
<body>
<h2>Preventing Form Refresh with event.preventDefault()</h2>
<form id="contactForm">
Name: <input type="text" name="name" required/><br><br>
Email: <input type="email" name="email" required/><br><br>
<input type="submit" value="Submit" />
</form>
<p id="message"></p>
<script>
var form = document.getElementById("contactForm");
var message = document.getElementById("message");
form.addEventListener('submit', function(event) {
event.preventDefault();
form.style.display = "none";
message.innerHTML = "<b>Form submitted successfully!</b>";
});
</script>
</body>
</html>
Using "return false" to Stop Page Refresh
Another method is to use return false in the form's onsubmit event handler. This cancels the default form submission.
Example
Here's an example with checkboxes that uses return false to prevent page refresh:
<html>
<body>
<h2>Preventing Form Refresh with return false</h2>
<form id="preferencesForm" onsubmit="submitForm(); return false;">
<input type="checkbox" id="bike" name="bike" value="Bike">
<label for="bike">I like biking</label><br>
<input type="checkbox" id="car" name="car" value="Car">
<label for="car">I like cars</label><br><br>
<input type="submit" value="Submit">
</form>
<p id="result"></p>
<script>
function submitForm() {
var form = document.getElementById("preferencesForm");
var result = document.getElementById("result");
form.style.display = "none";
result.innerHTML = "<b>Preferences saved successfully!</b>";
}
</script>
</body>
</html>
Using AJAX Form Submission
AJAX allows you to submit form data to the server without refreshing the page. This method sends data in the background using XMLHttpRequest.
Example
This example demonstrates AJAX form submission for a candidate registration form:
<html>
<body>
<h2>AJAX Form Submission</h2>
<form id="candidateForm">
<fieldset style="background: lightgrey; border: 2px solid #000; padding: 15px;">
<legend>Candidate Information</legend>
<input type="text" name="firstname" placeholder="First Name" required><br><br>
<input type="text" name="lastname" placeholder="Last Name" required><br><br>
<input type="email" name="email" placeholder="Email" required><br><br>
<input type="tel" name="phone" placeholder="Phone" required><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<p id="status"></p>
<script>
document.getElementById("candidateForm").addEventListener('submit', function(event) {
event.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/submit-candidate");
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("status").innerHTML = "<b>Application submitted successfully!</b>";
} else {
document.getElementById("status").innerHTML = "<b>Error submitting application.</b>";
}
};
// For demo purposes, we'll just show success without actually sending
document.getElementById("status").innerHTML = "<b>Form data prepared for submission!</b>";
});
</script>
</body>
</html>
Using Fetch API for Form Submission
The modern Fetch API provides a cleaner alternative to XMLHttpRequest for submitting forms without page refresh.
Example
This example uses the Fetch API to submit a form with a dropdown selection:
<html>
<body>
<h2>Fetch API Form Submission</h2>
<form id="raceForm">
<label for="racecourse">Select Race Course:</label>
<select name="racecourse" id="racecourse" required>
<option value="">Choose a course...</option>
<option value="ascot">Ascot</option>
<option value="belmont">Belmont Park</option>
<option value="churchill">Churchill Downs</option>
</select><br><br>
<input type="submit" value="Submit Selection" />
</form>
<p id="fetchResult"></p>
<script>
document.getElementById("raceForm").addEventListener('submit', function(event) {
event.preventDefault();
var formData = new FormData(this);
var resultDiv = document.getElementById("fetchResult");
fetch("/submit-race", {
method: "POST",
body: formData
})
.then(response => response.text())
.then(data => {
resultDiv.innerHTML = "<b>Selection submitted successfully!</b>";
})
.catch(error => {
resultDiv.innerHTML = "<b>Error: " + error.message + "</b>";
});
// For demo purposes
resultDiv.innerHTML = "<b>Race course selection processed!</b>";
});
</script>
</body>
</html>
Comparison of Methods
| Method | Browser Support | Best For | Complexity |
|---|---|---|---|
event.preventDefault() |
All modern browsers | Client-side validation | Simple |
return false |
All browsers | Inline event handlers | Simple |
| AJAX (XMLHttpRequest) | All modern browsers | Server communication | Moderate |
| Fetch API | Modern browsers | Modern server communication | Moderate |
Conclusion
Preventing form refresh is essential for modern web applications. Use event.preventDefault() for simple cases, and AJAX or Fetch API when you need to send data to a server without page reload.
