0

Hi guys i ran into a problem that i don't understand why, it is very strange or maybe i write the code wrongly so i hope you guys can point out the mistake or enlighten me .

so i was trying to submit a form to my database and before submit the form the validate function will validate the data, if there's an error it will notify the user

when i click submit button the form cannot be submitted and nothing happened, no error in terminal , no error on console , nothing ( it looks like you click on <button> inside a form, while the form is expecting <input type="submit"> to submit the form>

here's the full code https://github.com/johnlim5847/form-test

App.js ( i think nothing wrong in here)

  var express = require('express'),
         app = express(),
       http = require('http'),
       path = require('path'),
       MongoClient = require('mongodb').MongoClient,
       routes = require('./routes'),
       passport = require('passport');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        "use strict";
        if(err) throw err;
    // all environments
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/public/views');
    app.set('view engine', 'ejs');
    app.use('/static', express.static(path.join(__dirname, 'public')));
    app.use(express.cookieParser());
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({ secret: 'Super Duper Awesome Duck' }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    // development only
    if ('development' == app.get('env')) {
      app.use(express.errorHandler());
    }

    routes(app, db);

    http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
    });

    });

routes/index.js

var SessionHandler = require('./session');

module.exports = exports = function(app, db) {
var sessionHandler = new SessionHandler(db);
app.use(sessionHandler.isLoggedInMiddleware);
// Signup form
app.post('/register', sessionHandler.handleSignup);

app.use(function (req,res) {
 res.status(404).render('error', {
 url: req.originalUrl
  });
});

app.get('*',function(req, res){
  res.render('master', { title: 'form' });
});


}

routes/session.js

var UsersDAO = require('../users').UsersDAO
  , SessionsDAO = require('../sessions').SessionsDAO;

/* The SessionHandler must be constructed with a connected db */
function SessionHandler (db) {
    "use strict";

    var users = new UsersDAO(db);
    var sessions = new SessionsDAO(db);



   function validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors) {
        "use strict";
        var USER_RE = /^[a-zA-Z0-9_-]{2,25}$/;
        var PASS_RE = /^.{6,100}$/;
        var EMAIL_RE = /^[\S]+@[\S]+\.[\S]+$/;

        errors['publicUsername_error'] = "";
        errors['password_error'] = "";
        errors['confirmPassword_error'] = "";
        errors['email_error'] = "";
        errors['confirmEmail_error'] = "";

        if (!USER_RE.test(publicUsername)) {
            errors['publicUsername_error'] = "Try just letters and numbers, e.g: Ed, 69, Kelvin and etc";
            return false;
        }
        if (!PASS_RE.test(password)) {
            errors['password_error'] = "Password must be at least 6 characters long";
            return false;
        }
        if (password != confirmPassword) {
            errors['confirmPassword_error'] = "Password must match";
            return false;
        }
        if (!EMAIL_RE.test(email)) {
                errors['email_error'] = "Invalid email address";
                return false;
            }
         if (email != confirmEmail) {
            errors['confirmEmail_error'] = "Email must match";
            return false;
        }
        return true;
    }

    this.handleSignup = function(req, res, next) {
        "use strict";

        var email = req.body.email,
         confirmEmail = req.body.confirmEmail,
         password = req.body.password,
         confirmPassword = req.body.confirmPassword,
         firstName = req.body.firstName,
         lastName = req.body.lastName,
         penName = req.body.penName,
         publicUsername = req.body.publicUsername;

        // set these up in case we have an error case
        var errors = {'email': email,'publicUsername': publicUsername,'firstName': firstName,'lastName': lastName,'penName': penName}
        if (validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors)) {
            users.addUser(email, password, firstName, lastName, penName, publicUsername, function(err, user) {
                "use strict";

                if (err) {
                    // this was a duplicate
                    if (err.code == '11000') {
                        errors['email_error'] = "Email already in use. Please choose another";
                        return res.render("register", errors);
                    }
                    // this was a different error
                    else {
                        return next(err);
                    }
                }

                sessions.startSession(user['_id'], function(err, session_id) {
                    "use strict";

                    if (err) return next(err);

                    res.cookie('session', session_id);
                    return res.redirect('/');
                });
            });
        } else {
            console.log("user did not validate");
            return res.render("register", errors);
        }
    }
}

register.ejs

<div class="pure-u-1 text-center">
<form method="post" class="pure-form pure-form-aligned">
    <fieldset>
    <legend><h1 class="pure-splash-subhead midnightblue"><span class='lightblue'>Join</span> us today and start write things that <span class='maroon'>matter</span></h1>
    </legend>
        <p class="text-center red">{{email_error}}</p>
        <div class="pure-control-group">
            <label for="email">Email Address</label>
            <input required name="email" class="pure-u-1-3" type="email" placeholder="Email Address">
        </div>
        <div class="pure-control-group">
        <p class="text-center red">{{confirmEmail_error}}</p>
            <label for="confirmEmail">Confirm Email Address</label>
            <input required name="confirmEmail" class="pure-u-1-3" type="email" placeholder="Confirm Email Address">
        </div>
        <div class="pure-control-group">
        <p class="text-center red">{{password_error}}</p>
            <label for="password">Password</label>
            <input required name="password" class="pure-u-1-3" type="password" placeholder="Password">
        </div>
        <div class="pure-control-group">
        <p class="text-center red">{{confirmPassword_error}}</p>
            <label for="confirmPassword">Confirm Password</label>
            <input required name="confirmPassword" class="pure-u-1-3" type="password" placeholder="Confirm Password">
        </div>
        <br/>
        <br/>
        <div class="pure-control-group">
             <label for="firstName">First Name</label>
            <input required name="firstName" class="pure-u-1-3" type="text" placeholder="Your first name">
        </div>
        <div class="pure-control-group">
            <label for="lastName">Last Name</label>
            <input required name="lastName" class="pure-u-1-3" type="text" placeholder="and your last name">
        </div>
        <div class="pure-control-group">
            <label for="penName"><abbr title="A pen name, nom de plume, or literary double, is a pseudonym adopted by an author. The author's real name may be known to only the publisher, or may come to be common knowledge.">Nom de plume</abbr></label>
            <input required name="penName" class="pure-u-1-3" type="text" placeholder="Pen Name eg:J.R.R. Tolkien">
        </div>

        <div class="pure-control-group">
            <label for="publicUsername">Public Username</label>
            <input required name="publicUsername" class="pure-u-1-3" type="text">
            <p class="text-center red">{{publicUsername_error}}</p>
        </div>

        <div class="pure-u-1 ">
            <label for="conAndTerm" class="pure-checkbox">
                <input id="conAndTerm" type="checkbox"> I've read the <a class='link blue'href="#">terms and conditions</a>
            </label>
            <br/>
            <input type='submit'class="pure-button pure-button-secondary pure-u-1-3" value="Register">
            <br/>
        </div>
    </fieldset>
</form>
</div>

i think it might be a silly mistake i hope there's nothing wrong with my HTML tag LOL

John Lim
  • 3,019
  • 4
  • 31
  • 41
  • 1
    You can submit the form from a button via click handler, by finding the form and calling the submit() method of the form object. This isn't an EJS thing, more just a straight up HTML thing. See: http://stackoverflow.com/questions/290215/difference-between-input-type-button-and-input-type-submit – chsh Nov 20 '13 at 14:19
  • 1
    nonono i was giving an explanation on how it feels when i click on the button – John Lim Nov 20 '13 at 14:21
  • 1
    Make sure you have an action="/register" in your form. – Hector Correa Nov 20 '13 at 14:23
  • 1
    My apologies; I misread your initial post completely. Hector is likely correct, with no action defined the form won't go anywhere. – chsh Nov 20 '13 at 14:23
  • @HectorCorrea i can submit the form without the action="/register", of course it was before having the problem – John Lim Nov 20 '13 at 14:26
  • What does the resulting HTML look like? – chsh Nov 20 '13 at 19:43
  • when i click submit, nothing is change – John Lim Nov 21 '13 at 01:12
  • john lim, try to do this - app.get('/register', sessionHandler.handleSignupView); app.post('/register', sessionHandler.handleSignup); – wuiyang Aug 30 '14 at 13:54

3 Answers3

1

ok, so after short debugging session:

taken from Angular's docs

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

so it seems like you did not provide proper handling for form submit :-)

so either provide one or add the 'action' attribute to the form - that should "fix" it

let me know if that makes sense to you.

-1

You're missing the action attribute inside your form tag in register.ejs

It should be as following

<form method="post" action="/user/register" class="pure-form pure-form-aligned">

Now upon hitting "submit" a POST request will be generated and server shall look for a post type of route mentioned in action.


Another thing that's wrong with your code is ... you need to declare SessionHandler function using "exports" keyword as mentioned below.

exports.SessionHandler = async (req, res, next) => {
  // Session handler with arrow function
}

OR

exports.SessionHandler = async function (req, res, next) {
  // Session handler without arrow function 
}
Ibrahim Iqbal
  • 600
  • 3
  • 23
-2

I believe you need a space so that type='submit'class becomes: type='submit' class.

Dan Kohn
  • 33,811
  • 9
  • 84
  • 100