toomanyrichies toomanyrichies - 1 year ago 33
Javascript Question

What's the difference between $(form).submit and $(form).on("submit") in jQuery?

I wrote the following code, which doesn't result in an AJAX call in my browser:

$(document).ready(function () {
$('form').submit(function(event) {
var action = $(this).attr('action');
var data = $(this).serialize();
$.post(action, data, function(response) {

However, my instructor live-coded the following code in class, which does work:

$(document).ready(function () {
$("form").on("submit", function(event) {
var action = $(this).attr("action");
var formData = $(this).serialize();
$.post(action, formData, function(responseContent) {

As far as I can tell, the only meaningful difference between my code and his is the use of 'on' vs. 'submit' on line 2. In fact, on, the jQuery Foundation states that "This method is a shortcut for .on('submit', handler)...". Which leaves me confused as to why the two snippets behave differently.


If you look at the jQuery .submit() docs

This method is a shortcut for .on('submit', handler)

They behave the same

As you can see in jQuery's internal code, using the shorthand version will internally call .on()

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );