Prevent form submit event from reloading the page
In this article, we are going to discuss 2 options that how you can prevent your HTML form submit event from reloading the page. Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.
1. preventDefault
You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the <form> tag.
<form method="POST" action="your-page.php" onsubmit="onFormSubmit();">
<input type="submit" />
</form>
Then you can create the following Javascript function to prevent the page reload:
function onFormSubmit() {
event.preventDefault();
// your Javascript code here
}
In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevents the form submit event first, then it will run our Javascript code which is a good approach.
You can learn more about preventDefault from here.
2. return false
The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from the onsubmit event function. Let’s check this out.
<form method="POST" action="your-page.php" onsubmit="return onFormSubmit();">
<input type="submit" />
</form>
Then create your Javascript function as like that:
function onFormSubmit() {
// your Javascript code here
return false;
}
In this method, your Javascript code runs first before preventing the form submission.
Recommendation
We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.
Now that you have learned to prevent the form submit event. You can also display a pop-up for confirmation in case of the delete function. You can follow this tutorial to display a pop-up confirmation before submitting the form.