3

I am a beginner programmer. I am wondering how to submit a form, composed of JQuery date picker and radio buttons, using a button. I want to submit the form to a Mongo Database called test. In my home.html file I call the different stylesheets and javascript files I need. Then I set up an input field in the home.html and a button beneath the form to submit:

<!DOCTYPE html>
<html>
 <head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
   <meta charset="utf-8">

   <title>Home</title>
   <!-- Local CSS and JS -->
   <script src="/javascripts/home.js"></script>

   <!-- Materialize: Compiled and minified CSS -->
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">

   <!-- Materialize: Compiled and minified JavaScript -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
 </head>
 <body>
     <!-- Input field I want to submit -->
     <form method="post" action="/submit">
         <input id="test1" type="radio"><label for="test1">Test</label>
         <input id="test2" type="radio"><label for="test2">Test 2</label>
         <input id="test3" type="radio"><label for="test3">Test 3</label>
     </form>
     <!-- Button I want to use to submit -->
     <button type="submit" class="btn waves-effect waves-light" name="action">Sumbit</button>
     </div>
 </body>
</html>

Right now, I am loading this file by typing in localhost:3000/home.html. I want to use my index.js file to write the post method for submitting the data to my DB called test. After doing some research, I found that I'll need something to start my index.js like:

var express = require('express');
var router = express.Router();

//TALKING TO THE DB?
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var bodyParser = require('body-parser');
/*something would follow like?:
router.get('/submit', function(req, res) {
    var db = req.test;
});*/

For reference, I'm using the express skeleton so my app.js looks like:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Database
var mongo = require('mongodb');
var monk = require('monk');

//DB TEST
var db = monk('localhost:27017/test');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

However, I am confused as to how to set up routes that grabs the data from my input fields (using the submit button). Then I want to use a post method to write that information to my test database. Any help would be greatly appreciated! Thank you!

2 Answers 2

2

I found these two tutorials extremely helpful when starting to learn Node, MongoDB, and REST calls.

Tutorial 1

Tutorial 2

Here is some relevant code from the 2nd tutorial

Clientside:

// Add User button click
    $('#btnAddUser').on('click', addUser);
function addUser(event) {
    event.preventDefault();

    // Super basic validation - increase errorCount variable if any fields are blank
    var errorCount = 0;
    $('#addUser input').each(function(index, val) {
        if($(this).val() === '') { errorCount++; }
    });

    // Check and make sure errorCount's still at zero
    if(errorCount === 0) {

        // If it is, compile all user info into one object
        var newUser = {
            'username': $('#addUser fieldset input#inputUserName').val(),
            'email': $('#addUser fieldset input#inputUserEmail').val(),
            'fullname': $('#addUser fieldset input#inputUserFullname').val(),
            'age': $('#addUser fieldset input#inputUserAge').val(),
            'location': $('#addUser fieldset input#inputUserLocation').val(),
            'gender': $('#addUser fieldset input#inputUserGender').val()
        }

        // Use AJAX to post the object to our adduser service
        $.ajax({
            type: 'POST',
            data: newUser,
            url: '/users/adduser',
            dataType: 'JSON'
        }).done(function( response ) {

            // Check for successful (blank) response
            if (response.msg === '') {

                // Clear the form inputs
                $('#addUser fieldset input').val('');

                // Update the table
                populateTable();

            }
            else {

                // If something goes wrong, alert the error message that our service returned
                alert('Error: ' + response.msg);

            }
        });
    }
    else {
        // If errorCount is more than 0, error out
        alert('Please fill in all fields');
        return false;
    }
};

Serverside:

users.js

/*
 * POST to adduser.
 */
router.post('/adduser', function(req, res) {
    var db = req.db;
    var collection = db.get('userlist');
    collection.insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

app.js

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

app.use('/users', users);
Sign up to request clarification or add additional context in comments.

5 Comments

Please include some of the content or examples in your answer. If the links stop working one day, there won't be much left.
I'll go through and pull out some quotes, problem is just the sheer size of them. They are pretty lengthy
@ssube well said! But considering you're talking for the future, this website also might not be existing.
Then this is probably more appropriate as a comment, rather than an answer. In fairness, the question is pretty broad, basically "how do I use my stack" :/
I pulled out the specifics for setting up a post request and then actually making one on the frontend, hopefully that helps
0

Your question is a set of little questions or steps that can be solved in many ways(Each step depends on the tools and the code structure). So the most basic approach is to open the database connection in app.js and define a POST route using the Express router in a separate file or in the same app.js.

code:

 var router = express.Router();
 MongoClient = require('mongodb').MongoClient,
 Server = require('mongodb').Server;

 var mongoclient = new MongoClient(new Server("localhost", 27017));
 var db = mongoclient.db('mydb');

 router.post('/myroute', function(req, res){
   //Retrieve data sent by the client in the post request
     var param1 = req.body.param1;
  // Insert document in collection
   db.collection('mycollection').insert({ myfield: param1}, function(err, doc) {

    if(err) throw err;
    //Doc saved
   });
 });

I recommend you to see Node.js + MongoDB CRUD tutorials over the internet. Mongoose is a library that can help you defining schemas and dealing with the database.

Comments

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.