Explain Codes LogoExplain Codes Logo

How can I prevent refresh of page when button inside form is clicked?

web-development
prevent-default
event-handling
ajax
Nikita BarsukovbyNikita Barsukov·Feb 10, 2025
TLDR

To halt the form's submit action and the subsequent page refresh, utilize the preventDefault method on the submit event.

// Look mom, no refresh! document.querySelector('form').addEventListener('submit', function(e) { e.preventDefault(); });

This piece of code magic included in your script, targeting the form correctly, serves as an anti-refresh charm.

Fine tuning button rights: To refresh or not to refresh?

Even buttons have rights, including the right to trigger a form submission—its default behavior! If you want to revoke this right:

<!-- I have the power to not refresh! --> <button type="button" onclick="getData()">Click me</button>

Setting the button type to "button" pulls the plug on form submission. Additionally, associating an onclick event to the getData() function gives your button of the power to handle clicks without a page refresh flying in the face of the user. The getData() function should harness the event and invoke event.preventDefault() or return false to stop the page action dead in its tracks.

Smoothing over form behavior: Stay, page, stay!

In case your form is a natural submit-a-holic, you can delve into psychology and condition it to stop auto-refreshing on submission.

<!-- Not playing hard-to-get anymore! --> <form onsubmit="return false;">

By returning false from this event handler, the form breaks its submission habit. But if you prefer a more centralized, jQuery-based approach:

// Not today, submission! Not today! $('form').on('submit', function(event) { event.preventDefault(); });

Harnessing events this way, makes for smoother management, especially with multiple forms or dynamically added elements in the picture.

Taking the Ajax route: Refresh-free requests

To keep things smooth sailing, Ajax or the Fetch API can submit data without causing page refresh shock:

// Sending data behind the scenes document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); let formData = new FormData(this); fetch('submitform.php', { method: 'POST', body: formData }).then(function(response) { return response.json(); }) .then(function(data) { console.log(data); }); });

By resorting to a POST method, we ensure data travels incognito, in the HTTP request body, not parading around in the URL. This strategy keeps data more secure and can handle more payload than a GET request.

Not falling for false: Truth about returns

Hold up! Returning false in an event handler without preventDefault might not always stop the default action per browser rules. For maximum compatibility, explicitly call preventDefault. And if jQuery is the magic wand you wield, recall that return false also stops event propagation—an unexpected side effect. Choose your methods carefully!

Pro hacks: Extra credit strategies

Let's say you've stopped the form from going on a refreshing spree, but now, you want to remember the events of the past (requests/actions). Say hello to HTML5’s Web Storage: localStorage and sessionStorage—your best bet for persistent data storage:

// Who needs a diary? sessionStorage.setItem('key', 'value');
// Is that you, Memory Lane? let data = sessionStorage.getItem('key');

This technique ensures the user's progress isn't lost, providing a much smoother user experience even if they accidentally hit refresh or feel like playing hide & seek with the page.