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:
- 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 rename the element into another.
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:
- In html, add an "onsubmit" listener to this form and get returns from a function.
- In JavaScript, add a function called "getResponse" to the JavaScript block and always return false to prevent the submit.
<form onsubmit='return getResponse(this)'
...>
...
</form>
function getResponse(form) {
... // Getting response via ajax.
return false;
}