drume drume - 3 months ago 8
jQuery Question

Ajax submitHandler not executing

I want php file to execute through ajax but it just posts like normal through form and loads a new page. I have checked heaps of code on here and still it always does not execute through submitHandler and ajax. I have checked host provider and ajax is supported and i have done other tests with jquery and it works fine. Just can't get this to work how it should. the php file executes perferectly and inserts data into the database so I am guessing I am missing something with the validate code.



$("#emailForm").validate({

submitHandler: function(form) {
// event.preventDefault();
$.ajax({
url: $(form).attr("action"),
type: $(form).attr("method"),
data: $(form).serialize(),
success: function(response) {
document.getElementById("fee").style.display = "block";
}
});
return false;
}
});

#fee {
display: none;
}

<html>

<head>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>

</head>

<body>
<div class="screen">

<div class="contents">
<form class="cmxform" id="emailForm" method="post" action="process.php">
<fieldset>
<legend>Sign up now and secure your username!
</legend>
<p>
<label for="cname">Username (required, at least 5 characters)
</label>
<input id="cname" name="name" minlength="5" type="text" required>
</p>
<p>
<label for="cpassword">Password (required, at least 8 characters)
</label>
<input id="cpassword" name="password" minlength="8" type="password" required>
</p>
<p>
<label for="cemail">Email (required)
</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<div id='fee'>Signup Complete!
</div>
</div>
</div>
</body>

</html>




Answer

Try with, because using form object I am not sure its is Javascript DOM object ot jQuery object so I have convert object into jQuery object and used attr() method.

$(document).ready(function () {
$("#emailForm").validate({

   submitHandler: function(form) {
     $.ajax({
       url: $(form).attr("action"),
       type: $(form).attr("method"),
       data: $(form).serialize(),
       success: function(response) {
         document.getElementById("fee").style.display = "block";
       }
     });
     return false;
   }
 });
 });

Comments