Reputation: 126
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!
Upvotes: 3
Views: 21433
Reputation: 907
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.
Upvotes: 0
Reputation: 326
I found these two tutorials extremely helpful when starting to learn Node, MongoDB, and REST calls.
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);
Upvotes: 2