jQuery: form submission with Ajax

One of the most confusing parts of jQuery's study is actually the submission of a form through Ajax. More specifically, developers sometimes don't understand the difference existing between return false and preventDefault(). Both of these approaches can be used to prevent a form from executing its default action, that is, making a browser open the resource specified in the action attribute.

There's a fundamental difference between these two methods: return false entirely disables the submission of a form, whereas preventDefault() only prevents a browser from fetching the resource specified in the action attribute. If you use the first method, then you will be able to submit the form only once, because any further action will be disabled. Imagine what would happen when you have to validate a form through Ajax: if there are some user errors, then a user will correct all the fields containing errors but in some cases he won't be able to submit the form again, because the submission has actually been disabled.

Instead, if you use preventDefault(), only the default action of the form will be disabled, but not its submission. So here's the correct approach:

$('#testForm').submit(function(e) {
      // retrieve form data

            // use Ajax

Leave a Reply

Note: Only a member of this blog may post a comment.