197

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
bunkdeath
  • 2,348
  • 5
  • 21
  • 23
  • you have to specify the parameters, if you simple use window.location = window.location.href; it'll refresh the whole page & it'll resets all your previous requests. please check this:http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit – linguini Oct 18 '11 at 07:43
  • possible duplicate of [How do I make an HTML button not reload the page](http://stackoverflow.com/questions/1878264/how-do-i-make-an-html-button-not-reload-the-page) – Alex Angas Feb 14 '14 at 01:21
  • @bunkdeath: Suck [answer](http://stackoverflow.com/a/13262305/4509268) should be accepted. – Jad Chahine Sep 16 '16 at 11:58
  • @JadChahine sorry, I did not realised i have not accepted the answer, thanks for pointing this out. I was a beginner and did not know what I did or did not back then. But I wont be accepting the answer you mentioned, rather I will accept the one that helped me that time :) – bunkdeath Sep 18 '16 at 18:01

16 Answers16

486

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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
detale
  • 12,482
  • 4
  • 41
  • 42
  • 5
    Except this prevents HTML5 form validation (such as for input of type="email"). – 2540625 Apr 30 '15 at 22:02
  • 4
    You can also add `return false;` to the onclick: `onclick="getData(); return false;"` – JBaczuk Sep 14 '15 at 16:19
  • 5
    This is the best option. While "return false" might work inline there is not such option, that I know of, when adding event listeners. Specifying the type="button" really saves the day. – Forever Noob Oct 06 '16 at 15:51
90

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

<form method="POST">
    <button name="data" onclick="return getData()">Click</button>
</form>
Ivar
  • 6,138
  • 12
  • 49
  • 61
JNDPNT
  • 7,445
  • 2
  • 34
  • 40
29

All you need to do is put a type tag and make the type button.

<button id="btnId" type="button">Hide/Show</button>

That solves the issue

user8564339
  • 291
  • 3
  • 2
25

The problem is that it triggers the form submission. If you make the getData function return false then it should stop the form from submitting.

Alternatively, you could also use the preventDefault method of the event object:

function getData(e) {
    e.preventDefault();
}
Community
  • 1
  • 1
James Allardice
  • 164,175
  • 21
  • 332
  • 312
11

HTML

<form onsubmit="return false;" id="myForm">
</form>

jQuery

$('#myForm').submit(function() {
    doSomething();
});
Mehdiway
  • 10,337
  • 8
  • 36
  • 68
4

If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.

if you use js do like this

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

**If you use jquery use like this**


<form method="POST">
   <button name="data"  type="button" id="btnData">Click</button>
</form>




$('#btnData').click(function(e){
   e.preventDefault();
   // Code goes here
getData(); // your onclick function call here

});
Thusitha Deepal
  • 1,392
  • 12
  • 19
3
<form method="POST">
    <button name="data" onclick="getData()">Click</button>
</form>

instead of using button tag, use input tag. Like this,

<form method="POST">
    <input type = "button" name="data" onclick="getData()" value="Click">
</form>
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Manik Sood
  • 31
  • 3
2

A javascript method to disable the button itself

document.getElementById("ID NAME").disabled = true;

Once all form fields have satisfied your criteria, you can re-enable the button

Using a Jquery will be something like this

$( "#ID NAME" ).prop( "disabled", true);
repzero
  • 8,254
  • 2
  • 18
  • 40
1

This one is the best solution:

<form  method="post"> 
    <button  type="button" name="data" onclick="getData()">Click Me</button>
</form>

Note: My code is very simple.

HAPPY SINGH
  • 536
  • 4
  • 13
0

For any reason in Firefox even though I have return false; and myform.preventDefault(); in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault(); in the action attribute .

As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false; or javascript:this.preventDefault();. Do not try with javascript:void(0); which will break your code. Don't ask me why :-).

I don't think this is an elegant way to do it, but in my case I had no other choice.

Update:

If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit attribute, execute your function followed by the false return:

onsubmit="functionToRun(); return false;"

I don't know why all this trouble with Firefox, but hope this works.

raphie
  • 3,285
  • 2
  • 29
  • 26
0

Return function is not working in all the cases. I tried this:

<button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>

It didnt work for me.

I tried to return false inside the function and it worked for me.

function Reset()
{
    .
    .
    .
    return false;
}
Harsha Vardhini
  • 692
  • 6
  • 10
0

I was facing the same problem. The problem is with the onclick function. There should not be any problem with the function getData. It worked by making the onclick function return false.

<form method="POST">
    <button name="data" onclick="getData(); return false">Click</button>
</form>
Tasnim Fabiha
  • 1,148
  • 1
  • 17
  • 31
0

I updated on @JNDPNT answer, this way the function (getData()) doesn't have to return false;

 <form method="POST">
    <button name="data" onclick="getData(); return false;">Click</button>
</form>
iYazee6
  • 826
  • 12
  • 22
0

A simple issue I found is that if the function that you're trying to call is called submit, the form will be submitted either way.

You will need to rename the function for the page to not be reloaded

Carter
  • 59
  • 1
  • 2
  • 3
-1

Add e.preventDefault(); in the starting of the function to be called when the button is clicked

Example:

    const signUp = (e) => {
    e.preventDefault()
    try {
    } catch (error) {
      console.log(error.message)
    }
  }

The button code:

            <input
              type='submit'
              name='submit-btn'
              id='submit-btn'
              value='Sign Up'
              onClick={signUp}
            />
-2

You can use ajax and jquery to solve this problem:

<script>
    function getData() {
        $.ajax({
            url : "/urlpattern",
            type : "post",
            success : function(data) {
                alert("success");
            } 
        });
    }
</script>
<form method="POST">
    <button name="data" type="button" onclick="getData()">Click</button>
</form>
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • This answer is overly complicated, let alone requiring an outside library to prevent the OP's issue where other, simpler, methods can be used. – reZach Apr 07 '19 at 23:16