JBB JBB - 1 year ago 77
jQuery Question

Why jQuery $('#form').submit(); works perfectly BUT Not $('#form').submit(function(){...});?

When I try to submit a form with jQuery, a simple


works perfectly but


is purely and simply ignored.
No error message, no nothing.
It move on and proceed the rest of my code just fine.

The closer issue I've found here is this one:
JQuery form submit with function not working
It works better but the submit() reload the page and cancel the benefit of the Ajax.
So unfortunatly, it doesn't works for me :(

Here is my entire code (I reduced the true project to the simplest for test purpose) :

<!doctype html>
<meta charset="utf-8">
<title>please help</title>
<link href="../htdocs/css/styles.css" rel="stylesheet">

<form id="myForm" method="post">
<input name="key01" type="checkbox" id="key01" checked>
<input name="key02" type="checkbox" id="key02" checked>
<input name="key03" type="checkbox" id="key03" checked>
<input name="key04" type="checkbox" id="key04" checked>
<input name="key05" type="checkbox" id="key05" checked>

<div id="testBtn">test submit</div>

<div id="resultDisplay"></div>

<script src="../htdocs/js/jquery-2.2.4.min.js"></script>
<script src="../htdocs/js/icheck.min.js"></script>
<script type="application/javascript">
$(function () {
$('#testBtn').click(function () {
console.log('click out');
$('#myForm').submit(function () {
console.log('click In');
method: 'POST',
url: 'myResult.php',
data: $(this).serialize()
}).done(function (data) {
console.log('data back');
}).fail(function () {


The only console.log I have is the first one outside the submit function.
I tried with alert instead, with get method, with differents jQuery versions on Apache and nginx server...
it's all the same :'(

PHP : 5.6.23
jQuery 2.2.4 (several versions tested)

Please help, I'm desperate :(

Answer Source

Actually $('#form') returns an array and the properly way of performing it is by specifying what array's item will perform the given function:

    //do the stuff

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download