What I’m looking for: way to have innate html 5 form validation using the required=”true”, where if the user clicks the “Submit” button, the first thing that happens is the automatic html 5 validation where it checks to see if “username” is provided by the user. If it’s not, then it displays the ugly error bubble.
If it is provided, however, I then have my own custom validation for checking against the db if the username exists. If it does, then return true (allow submission), false otherwise. What’s happening: the form is getting submitted. It’s like it does not wait for the success callback to return true/false on whether or not it should be submitted.
I hope that’s clear enough! Code below:
html:
<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>
js:
$("form").submit(function() {
$.ajax({
url: 'usernamechecker.php?username=' + $("#username").val(),
success: function(resp) {
if (!resp.UsernameExists) {
return true; // allow form submission
}
return false; // do not allow form submission
}
});
});
You need to add “async: false” as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.