The second POST
with your form data is sent because your submit
event handler doesn't return False
. If you want to prevent the form from submitting when clicking the submit button, you have to return False
in the event handler. The event handler can also be told to prevent form submission by calling e.preventDefault()
on the event object that is being passed to the submit
handler.
The reason for this behaviour is that, by default, the event fired when a submit button is clicked submits the forms at the very end of the event handling chain. So what happens is that in your event handler you are send a AJAX POST
call (which is asynchronous), and the very next moment the handler returns without prevent the event from form submission. This results in both AJAX
and form
being sent.
e.preventDefault()
tells the event e
to avoid doing the default action specific to this event, in this case form submission. With this added, when $.ajax
finishes and all the handlers are done handling the event the default handler is checked if it's allowed to be run. Since you have prevented it, nothing happens.
The very same method can be used to, e.g. prevent the webpage following a link <a>
when clicked.