0

I have this POST request for a registration page. It checks to see if a username is already being used by another user:

router.post ('/register', function(req, res) {
User.findOne({username: req.body.username}, function(err, existingUser) {
    if(existingUser) {
        req.flash('errors1', req.body.username + ' already exists.');
        return res.redirect('/register');
    }
//some more code down here if the username is unique

And here is the form (I'm using EJS):

<form method="POST" action="/register">
    <% if (errors1.length > 0) { %>
        <div class='form-group has-error'>
            <label for="username">Stock Ticker</label>
            <input type="text" name="username" class="form-control" id="username"/>
            <span class="help-block"><%= errors1 %></span>
        </div>

Basically, if the username entered is not unique, a message will appear just below the form telling the user that the username cannot be used. But this message only shows up after a user has hit the SUBMIT button.

How can I incorporate AJAX into this? I've never really used AJAX before, and have been going through the documentation and watching tutorials, but I just can't wrap my head around how I could incorporate AJAX into this piece of code.

1 Answer 1

1

You should create new api to do the check and trigger this request when input control lose focus,maybe the code would like this below:

server.js:

router.post ('/check_username', function(req, res) {
    //CODE:check your username 
})

html:

<div class='form-group has-error'>
        <label for="username">Stock Ticker</label>
        <input type="text" name="username" class="form-control" id="username"/>
        <span class="help-block"><%= errors1 %></span>
</div>

js(Jquery):

$("#username").focusout(function(){
        var value = $("#username").val();
        //CODE:send the request and display result;
        $.post('/check_username',{username:value},function(data){
        //CODE:handle result
        })
    });
Sign up to request clarification or add additional context in comments.

2 Comments

You could also do it as the input value is changed, but I would suggest using a debounce/throttle function so that you don't get rapid fire calls to your server.
yes,trigger the request when content changed,the debounce/throttle is required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.