0

I have been working on the final check part for the pset8 exercise. In the registration part, when the username is taken, I could get an alert. However, I couldn't seem to stop it from logging in. I have looked at what's available here and what maybe useful online but couldn't figure it out. I am wondering if I have missed something in the register route instead?

Anyway, my code in the register.html:

<script>
    $(document).ready(function() {
        $("form").submit(function(event){
            $.get("/check", {username: $("#username").val()}, function(data) {
                    if (data == "false")
                    {
                        alert("Username taken");
                        event.preventDefault();
                        return false;
                    }
            });
        });
    });
</script>

<form action="/register" method="post" id="register">
    <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="password2" placeholder="Password Confirmation" type="password">
    </div>
    <button class="btn btn-primary" type="submit" id="button">Register</button>
</form>

Any pointer is hugely appreciated!

2

You have to stop the submission now (in the submit event listener), and in case of success submit in the AJAX callback.

Submitting via JavaScript will not trigger another submit event.

4
  • Thanks Blauelf. I tried what u suggested. Or at least based on my understanding of your suggestion. I still haven't worked it out. When I tried to submit inside the ajax callback. I get repeated submit attempts showing on terminal but nothing on the front end. Can u be a bit more specific on what u meant? I am fairly new to the whole concept so I might well have missed some many things here... – Jin Chen Feb 23 '19 at 0:44
  • The submit action needs to be prevented, so you would do that in the submit callback, not in the AJAX callback that gets executed much later, when the submit action already has been processed. In the $.get callback, if the username is not taken, you'd document.getElementById("register").submit(); or an equivalent (maybe $("#register").submit(); or similar, am not much into jQuery) – Blauelf Feb 23 '19 at 9:36
  • Thank you @blaueff! I finally figured it out the logic. – Jin Chen Feb 25 '19 at 12:59
  • could you elaborate Jin? – sspec56 Mar 7 '19 at 10:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .