In the 2019 edition of CS50 Finance there is a final subproblem where you have to use AJAX to ask the server if a username a new user is trying to register with is already taken, and then alert the user and block form submission if it is. Otherwise, you let the user register and proceed.
Below, please find my script (my first time using Javascript and JQuery), along with the associated HTML. Assume that the "/check" route returns "true" or "false" depending on whether the username is already taken or not. I am 100% confident this route functions properly and returns that appropriate value to function(data).
At present when I run the web app and enter a username that is already taken, the app delivers the appropriate alert. However when I try to submit a username that is not taken, it simply refuses to submit. Any guidance here on what is happening within my code would be very appreciated, as I feel at a complete loss. Happy to provide more details as needed.
Thank you!
Here is my script:
<script>
$(document).ready(function() {
$("#check").submit(function(event){
var x;
$.get("/check", {username: $("#username").val()}, function(data) {
if (data == "false")
{
alert("username taken");
x = false;
}
else if(data == "true")
{
x = true;
}
});
return x;
});
});
</script>
And please find the html form below:
<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>
console.log(x);
before you return it, and check its value.data
might not be what you expect, which would mean you returnundefined
. Also check your browser dev tools' network tab.