jQuery validation conflicting with AJAX call -
i've got form pretty simple validation snippet simple ajax call, except when try put 2 i'm running problems. if put validation snippet ahead of ajax call validation works ajax call not submit. if put ajax call ahead of validation ajax call works , validation doesn't. i'm lost , been banging head hours on one. appreciated!
$("#headerform").submit(function(){ var validate = true; $("#headerform :input").each(function(){ var $this = $(this); if(this.id == "phonenumber" && $this.val().length < 10 ){ alert("please enter valid phone number"); validate = false; return false; } else if(!this.value.length){ alert("field required"); validate = false; return false; } }); return validate; var name = $("#name").val(); var phone = $("#phone").val(); var datastring = 'name='+ name + '&phone=' + phone; $.ajax({ type: "post", url: "/bin/headerform", data: datastring, success: function() { $('#headerform').html("<div id='message'>thank you</div>"); } }); return false; });
the best practice move validation code function, call in submit handler:
function validateform() { var validate = true; $("#headerform :input").each(function () { var $this = $(this); if (this.id == "phonenumber" && $this.val().length < 10) { alert("please enter valid phone number"); validate = false; return false; } else if (!this.value.length) { alert("field required"); validate = false; return false; } }); return validate; }
then submit handler:
$("#headerform").submit(function () { if (validateform()) { var name = $("#name").val(); var phone = $("#phone").val(); var datastring = 'name=' + name + '&phone=' + phone; $.ajax({ type: "post", url: "/bin/headerform", data: datastring, success: function () { $('#headerform').html("<div id='message'>thank you</div>"); } }); } return false; });
Comments
Post a Comment