Preventing Page Refresh with Form Buttons
When creating forms with buttons, it's common to encounter an issue where button clicks trigger unwanted page refreshes. This can be problematic, especially if the page contains dynamically loaded data that gets reset upon refresh.
Issue Description
In the provided code snippet:
<form method="POST"> <button name="data" onclick="getData()">Click</button> </form>
Clicking the button calls the getData() function, but it also automatically refreshes the page. This occurs because the default type for a button in a form is "submit," which initiates a form submission and reloads the page.
Solution
To prevent page refresh, modify the button's type attribute to "button" like this:
<button name="data" type="button" onclick="getData()">Click</button>
By setting type="button", the button no longer initiates a form submission. Instead, it behaves like a regular button that solely triggers the specified onclick event without affecting the page.
Explanation
The type attribute defines the type of button. The possible values are:
By setting type="button", you effectively convert the button into a non-submitting button that simply triggers the desired JavaScript function without causing page refreshes.
The above is the detailed content of How to Stop Form Buttons from Refreshing the Page?. For more information, please follow other related articles on the PHP Chinese website!