0

I have the following:

<form id="form" action="xxx" method="get">
  <input type="checkbox" name="cb">
  <button onclick="update();">Update</button>
</form>

<script>
  function update() {
    var data = $("#form").serialize();
    $.ajax( {
      url: "/api/m/x",
      type: "post",
      data: data
      }
     ).done(function(results,status) {
          alert(status);
       }).fail(function(error, status) {
          alert(status);
      });
   }
</script>

When I clicked the Update button, the Ajax call was made to /api/m/x and one of the alerts was triggered. So far so good. However, after I closed the alert dialog, the form is submitted! The browser is sent to xxx?cb=on, for example if I ticked the check box.

Why is this happening? My form does not have an <input type='submit'> element. Who is triggering the submit of the form?

I tried adding return false; to the update function but the behavior is still the same.

Old Geezer
  • 14,854
  • 31
  • 111
  • 198

2 Answers2

1

If you have button in form, form is submitting when you click this button

try like this:

<form onsubmit="update();return false;">
1

The <button> tag in a form is a submit button unless you specify type=button
Also the return false should be on the onsubmit event

<form id="form" action="xxx" method="get" onsubmit="return update();">

function update() {
...
    return false;
}
Musa
  • 96,336
  • 17
  • 118
  • 137