Having a problem where the form submits before the validateUsername function has a chance to complete the username check on the server-side.
How do I submit the form only after the validateUsername function completes? Hope this is clear...
form.submit(function(){
if (validateUsername() & validateEmail() & validatePassword()) {
return true;
} else {
return false;
}
});
function validateUsername(){
usernameInfo.addClass("sign_up_drill");
usernameInfo.text("checking...");
var b = username.val();
var filter = /^[a-zA-Z0-9_]+$/;
$.post("../username_check.php",{su_username:username.val()},function(data) {
if (data=='yes') {
username.addClass("error");
usernameInfo.text("sorry, that one's taken");
usernameInfo.addClass("error");
return false;
} else if (!filter.test(b)) {
username.addClass("error");
usernameInfo.text("no funny characters please");
usernameInfo.addClass("error");
return false;
} else {
username.removeClass("error");
usernameInfo.text("ok");
usernameInfo.removeClass("error");
return true;
}
});
}
More verbose version of Olafur's answer - The AJAX call is made and the function returns without waiting.
The callback doesn't finish until you've submitted the form.
What you should do is have the button/trigger calling the AJAX validation, and the callback should submit the form instead of returning true.
The jQuery form validation plugin takes care of this for you -- I highly recommend it.
Some sample code:
$("#myform").validate({
rules: {
email: {
required: true,
email: true
},
username: {
required: true,
remote: {
url: "../username_check.php",
type: "post",
}
}
}
}
});
I dealt with a similar issue recently. Under some circumstances, pressing enter on an input field might make the form submit. I attempted to remedy this in a number of ways, and then the specifications required changed so that pressing the Enter key or Go on a device, will allow a form submission. My solution was just what made sense to me at the time.
var form_submit = false;
function validateInput () {
var field_value = $('#username').val();
$.post('validation.php', {'input': field_value }, function (d) {
if (d.valid) {
form_submit = true;
$('form').submit();
} else {
//error message or whatever
}
}, 'json');
}
$('form').submit( function () {
if ( form_submit ) {
return true;
} else {
validateInput();
return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With