How to Resolve jQuery submit() Not Working

jQuery submit()

You might want to block submit of a form by jQuery's submit() for getting an ajax response or doing something else in the same web page rather than going to another web page. When your found the submit() did not work at all, it might be the reasons:

  • One element is the same name with "submit" in the form:
  • To resolve this, please rename the element into another.

  • Some elements with their identities are loaded externally via ajax after the document is already ready, jQuery is unable to recognize the elements:
  • To resolve this, please put the jQuery submit event listener in ajax block like this:

    $.ajax({
      ...
      context : this,
      success : function(response) {
        ...
        $("#the_form").submit(function(event) {
          event.preventDefault();
          ...
        });

      }
    });

Solutions

If you have tried all the above solutions but failed, the last resort is to use plain-old JavaScript to block the submit. For example:

  1. In html, add an "onsubmit" listener to this form and get returns from a function.
  2. <form onsubmit='return getResponse(this)' ...>
      ...
    </form>
  3. In JavaScript, add a function called "getResponse" to the JavaScript block and always return false to prevent the submit.
  4. function getResponse(form) {
      ... // Getting response via ajax.
      return false;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *