Skip to content
Advertisement

How can I prevent refresh of page when button inside form is 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?

Advertisement

Answer

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

<form method="POST">
    <button name="data" onclick="return getData()">Click</button>
</form>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement