Prevent form submit event from reloading the page

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" />

Then you can create the following Javascript function to prevent the page reload:

function onFormSubmit() {

	// your Javascript code here

In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevent the form submit event first, then it will run our Javascript code which is a good approach.

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" />

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.


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.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post

Leave a Reply

Please disable your adblocker or whitelist this site!