I’m using the validation plugin for jQuery to validate a form before making an Ajax call, but for some reason every time I submit the form the page refreshes. Here is my validation function:
//Invite form validation
$("#inviteForm").validate({
//Rules for invite validation
rules: {
name: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
name: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
$("#inviteModal").html(data);
if(data.indexOf("Thank you") >= 0 ){
invites -=1;
$("#overlay").css("display", "none");
$("#inviteModal").fadeOut(5000);
}
}
});
return false;
}
});
I have it inside a $(document).ready, but I didn’t post the whole thing because I have a few other functions in there. And this is the code for the form:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteModal").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<form id=\"inviteForm\" >"+
"<p>Name: <input type=\"text\" name=\"name\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>"+
"</form>");
}
</script>
</div>
Whenever I submit the form it refreshes the page without executing the Ajax call and tacks the form data on to the URL, such as ?name=bobby&email=williamrump%40aol.com&submit=Invite. Why might it be refreshing the page without making the Ajax call, and what might I be able to do to prevent it?
Seems like you are creating your form after trying to attach the validator.
This, is one of the few reasons that may cause this:
I would check for:
document.ready()around jQuery code, to make sure you are attaching the validator events after creating it.,in the options object sent to the validator. Some browsers (like IE) might fail with it.console.log()on your submit handler, to see if anything goes through to your validator.Last minute note: Seems like my first suggestion, also provided in the comments to your question was the issue. So you may take the rest as future check list for this kind of issues 🙂