I am trying to write the script for a form such that if a username is taken, the user is alerted that it is taken, and submission of the form is blocked. If the username then types in the correct password, the script allows the form to be submitted. The script uses $.get() to query a SQL database, returning true to the callback function if the username is available, and false if it is not. I am positive this part of my application works correctly.
Below is my script, with pseudo code entered for the part I cannot solve, as well as the form itself.
<script>
$(document).ready(function() {
$("#check").submit(function(event){
$.get("/check",{username: $("#username").val()} , function(data) {
if (data == false){
alert("Taken");
}
});
// if callback returns false ie. data == false,
// return false (thus blocking form submission);
// else if callback returns true, ie. data == true,
// return true (thus allowing form submission);
});
});
</script>
<form action="/register" method="post" id="check">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmation" placeholder="Confirm password" type="password">
</div>
<button class="btn btn-primary" type="submit" id="register">Register</button>
</form>
My problem is that I cannot seem to base the behavior of the second function $("#check").submit(function(event)
, which controls the form's submission on the value returned to the callback function in jQuery.get(), which tells me if the username is taken or not.
Any assistance in how to go about thinking of how to solve this would be really appreciated, and happy to provide clarification as needed.