prevent page refresh on form submit

How to Prevent Page Refresh on Form Submit

By default, when we submit form on a web page, it automatically refreshes the page after submitting form data to web server. But sometimes you may want to prevent page refresh on form submit. This is required if you need to send form data via AJAX. In this article, we will learn how to prevent page refresh on form submit.


How to Prevent Page Refresh on Form Submit

Let us say you have the following form.

<form id='myform'>
   ...
</form>

You can prevent page refresh using plain JavaScript, or third party libraries like jQuery. We will look at both these methods.

1. Using JavaScript

Here is the code to prevent page refresh using JavaScript.

var form = document.getElementById("myform");
function handleForm(event) { event.preventDefault(); } 
form.addEventListener('submit', handleForm);

In the above code, we first get the form element by its ID. Then we define an event handler for the form, called handleForm. We define it to call event.preventDefault() which basically disables the default behavior of the element when the handler is triggered. Alternatively, you can also return false value here. In this case, the default behavior is page refresh. Lastly, we add this event handler to ‘submit’ event of the form.

2. Using jQuery

You can also use jQuery to prevent page refresh.

$("#myform").submit(function(e) {
    e.preventDefault();
});

Here we directly call e.preventDefault() function where e stands for event, on submit() function, which is the event handler for jQuery. Instead of calling preventDefault() function, you can also return false value here.

3. Using onsubmit attribute

You can also use onsubmit attribute of form element, to define which function to call, and disable page refresh.

<form id="myform" onsubmit="yourFunction();return false">
   ...
</form>

In the above code, when the form is submitted, yourFunction() is called first, and then false is returned, thereby preventing its default behavior of page refresh.

In this article, we have learnt several simple ways to prevent page refresh on form submit.

Also read:

How to Check if Object is Array in JavaScript
Regular Expression to Match URL Path
How to Split String Every Nth Character in Python
How to Reverse/Invert Dictionary Mapping in Python
How to Sort List of Tuples By Second Element in Python

One thought on “How to Prevent Page Refresh on Form Submit

Leave a Reply

Your email address will not be published.