Unable to send form data into MongoDB database using Node.js - javascript

So I've been trying to get the data from my form and input it into my database for ages and it just isn't working. There are no errors and nothing is logging.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Signup for NGOs</title>
</head>
<body>
<form class="mt-4 mr-4 ml-4" id="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name of NGO">
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Address">
</div>
<div class="form-group">
<label for="phone">Contact Information</label>
<input type="number" class="form-control" id="phone" placeholder="Contact Number">
</div>
<div class="form-group">
<label for="requirements">Requirements (Seperate by Commas)</label>
<input type="text" class="form-control" id="requirements" placeholder="Requirements">
</div>
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
</form>
<!-- Optional JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="signup.js"></script>
</body>
</html>
And this is my Node.js code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
// I've replaced my original username and password with placeholders
var uri = "mongodb+srv://username:password#helpbook-rlpsi.gcp.mongodb.net/test?retryWrites=true";
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
app.post('/signup', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
dbConn.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
});
I don't know what's going wrong. My data isn't being uploaded to the database and for some reason none of the console.log() statements are being executed.

The promise probably resolves before the signup handler is called.
Try the following:
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
dbConn.then(function(client) {
app.post('/signup', function (req, res) {
delete req.body._id; // for safety reasons
client.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
})
.catch(function(err){
console.log(err)
});

Looking at your question specifically, you are not using any action in your form.
<form class="mt-4 mr-4 ml-4" id="form" method="post" action="/signup">
...
</form>
So it is not getting posted to your route. (That's why I specifically asked if console logging before the dbconn is working or not)

Related

calculator in express js, update answer in the same page

I build a simple express js calculator and I want the calculate to show the answer on the same page with the text boxes where I enter the numbers, now after I click calc I move to a blank page with the answer, instead I want a section under the calc button which show "Answer: XXX"
app.js
const express= require("express");
const bodyParser=require("body-parser");
const app= express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"))
app.get("/",function(req,res){
res.render('home');
});
app.get("/add",function(req,res){
res.render('add');
});
app.post("/add",function(req,res){
var num1=Number(req.body.n1);
var num2=Number(req.body.n2);
var result=num1+num2;
res.send("Answer: "+result);
});
add.ejs
<!DOCTYPE html>
<html dir="rtl">
<head>
<title>calc add</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<form action="/add" method ="post">
<input type="text" class="input" name="n1" placeholder="enter x1"><br>
<br>
<input type="text" class="input" name="n2" placeholder="enter x2"><br>
<br>
<button type="submit" class="submit" name="Submit">calc!</button>
</form>
<br>
<a class="back" href="/">home</a>
</body>
</html>
You can use fetch to make the POST request and get the answer.
<p id="result"></p>
<script>
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
fetch(this.action, {method: this.method, body: new FormData(this)})
.then(res => res.text()).then(ans => {
document.getElementById("result").textContent = ans;
});
});
</script>

How to submit form data to mongodb atlas

i want a user to input data in a form i created and i want the data to be sent to mongodb atlas.
so i host the form locally and it gives me an error "require is not defined".
my question is do i have to bundle the mongodb module or is there a way to do it without bundleing.
this is the code.
I USE THE VSCODE LIVE EXTENSION TO HOST.
document.querySelector(`input[type="submit"]`).onclick = () =>
{
var x = document.forms["form1"]["username"].value;
var password = document.forms["form1"]["password"].value;
var email ={
name : `${x}`,
password : `${password}`
};
if(document.querySelector(`input[type="checkbox"]`).checked){
var json = JSON.stringify(email);
var MC = require('mongodb').MongoClient;
var url = "mongodb+srv://<username>:<password>#cluster0.xjoqb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
MC.connect(url, (err, db) => {
if (err) {
throw err;
}
console.log(`Connected`);
var data = db.db(`mydb`);
data.createCollection(`first`, (err, res) => {
if (err) throw err;
console.log(`collection created`)
});
data.collection(`first`).insertOne(email, (err, res) => {
if(err) throw err;
console.log(`inserted`);
db.close();
});
});
}
}
This is the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="google-signin-client_id" content="707054985283-cirkm54740d0pm838hrgq7etkp3hu3ej.apps.googleusercontent.com">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<fieldset>
<h1 id="greeting">Welcome Back</h1>
<p id="greeting2">Let's Get Signed In</p>
<form name="form1" class="form" method="POST" autocomplete="off" spellcheck="false">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div class="con1">
<input type="text" id="name" name="username" placeholder="Enter Your Email Address">
<img src="https://img.icons8.com/windows/50/000000/name.png" class="nameicon">
</div>
<div class="con2">
<input type="password" id="pass" name="password" placeholder="Enter Your Password">
<img src="https://img.icons8.com/windows/50/000000/password.png" class="passicon">
</div>
</form>
Forgot Password?
<div id="alm">
<input type="checkbox" id="remember" name="remem">
<label for="remem">Remember Me</label>
</div>
<form class="button1">
<input type="submit" name="submit" id="submit1">
</form>
</fieldset>
</body>
<script src="script.js"></script>
</html>
Databases (remote or local) are server side services. You need a back end app that handles the post request from the form located in the front end part and then from the backend trigger any action into Mongo Atlas.
Going with a NodeJS & Express stack could be a good option for you (you will also need to work with mongo in the backend, but in this case you will be storing the data in a remote Mongo Database).

Why socket.io is not working with Ajax properly?

For a while i interest nodejs and socket.io. I know i installed nodejs and socket.io properly. I prepared a form then i got values with javascript then by sensing with ajax to my php file, then i got what a want properly. But time to making amit with socket.io i always revieve this. message
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUs8K 404 (Not Found) polling-xhr.js:203
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUsVI 404 (Not Found) polling-xhr.js:203
.
.
.
Here is my server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
//console.log('a user connected'); //this works
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Server.js works properly i tested using this console.log('a user connected'); and it works well.
Then i tried to emit real datas.
here is my html file making ajax with
<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<form method="post" action="">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" id="email" >
</div>
<div class="form-group">
<label for="passwprd">Password</label>
<input type="password" class="form-control" id="password">
</div>
<button type="button" id="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#submit").on("click",function(){
var dataString = {
email : $("#email").val(),
password : $("#password").val(),
};
$.post("isle.php",{data:dataString},function(response){
// console.log(response);
var socket = io();
socket.emit('chat message', dataString);
return false;
},"json");
});
});
The last one is isle.php
<?php
$data=$_POST["data"];
$gonderilecek=[
"email_adres"=>$data["email"],
"sifre"=>$data["password"],
"mesaj"=>"mesajımız burada"
];
echo json_encode($gonderilecek);
I could not solve the problem any one can help me

How to send email via real server(SendGrid)

For my website, I am trying to send email to the users. I used sendgrid provider for sending the mail with nodeJS. I am new to nodeJS, I have sent the mail via the command prompt as per their instructions on their page. But I don't how to implement it on the real server. For sending emails via sendgrid I installed their package. And I want to send an email to a particular event.
function goMail()
{
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(MY_API_KEY);
const msg = {
to: '********1234#gmail.com',
from: '12345***#gmail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
}
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container">
<h2>Vertical (basic) form</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" onclick="goMail();">Submit</button>
</form>
</div>
</body>
</html>
Please explain to brief how do they work on the real server.
You cannot directly include index.js file in HTML and invoke the Nodejs function. instead you should be using Express framework at Nodejs and use jQuery to post the form data. Please follow the instructions provided in the below link:
https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
Hope this answer points you to the right direction and resolve your issue.
If you have implemented your server code then just add the following route in app.js file for creating an API for sending an email to the users
app.get('/sendEmail', (req, res) => {
let sendgrid = require('sendgrid');
let SG = sendgrid('your sendgridKey');
let request = SG.emptyRequest();
request.method = 'POST';
request.path = '/v3/mail/send';
request.body = (new sendgrid.mail.Mail(
new sendgrid.mail.Email(req.body.from),
req.body.subject, // subject
new sendgrid.mail.Email(req.body.to),
new sendgrid.mail.Content('text/html', 'your html')
)).toJSON();
SG.API(request, (err, response)=> {
if (response.statusCode >= 200 && response.statusCode < 300) {
res.send(response);
});
});
or you can define this function outside of the router so that you can call this function as middleware in any route.

Cannot post form data via HTML/JavaScript/Express Node app

I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body

Categories

Resources