prevent refresh of page when button inside form clicked

I have an issue while using buttons inside form. I want that button to call function. It does, but with unwanted result that it refresh the page.

My simple code goes like this

<form method="POST">
    <button name="data" onclick="getData()">Click</button>
</form>

On clicking the button, the function gets called with page refreshed, which resets all my previous request which affects the current page which was result of the previous request.

What should I do to prevent the page refresh?


Solution 1:

Add type="button" to the button.

<button name="data" type="button" onclick="getData()">Click</button>

The default value of type for a button is submit, which self posts the form in your case and makes it look like a refresh.

Solution 2:

Let getData() return false. This will fix it.

<form method="POST">
    <button name="data" onclick="return getData()">Click</button>
</form>