Html - Javascript: Mysql doesnt saving data in database - javascript

i just have a register button in my html as follows, which calls the register() function from the insert.js file. When i run alone the insert.js script it writes data to my database. The problem is that when i combine it(the js script) with this html code, it writes nothing. What im doing wrong?
<form method="post">
<div class="inputs">
<div class="input">
<input placeholder="Email" name="email" type="text">
<img src="img/mail.svg">
</div>
<div class="input">
<input placeholder="username" name="username" type="text">
<img src="img/user.svg">
</div>
<div class="input">
<input placeholder="password" name = "password" type="password">
<img src="img/pass.svg">
</div>
</div>
<button onclick="register()" >Register</button>
</form>
<script src="insert.js"></script>
my insert.js file
function register()
{
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "assessment"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (username, password) VALUES ('james', 'bond007')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
}

Well, it seems to me that js file its node which is back-end, installed on a server and the HTML it's front-end which runs on the user machine, that js it's fine but should be accessible for the HTML, the front, whoever uses your application, through an endpoint which you can do on node, but I could be wrong if you are using some kind of framework...

Related

DataBase connection when clicked

I'm learning how to make websites and I ran into a problem that I can't solve, I hope you can explain it to me. I have set up and created a database (I am sure it works and I have tried to use it), but I do not know how to use it in a real project. I have a small page with a few fields and a button, and when I click on it, I connect to the database (I'll add some functions later). But I can't figure out how to do that. Can you help me?
Here's my HTML code:
<div class="login-card-container">
<div class="login-card">
<div class="login-card-header">
<h1 style="font-size: 23px">Tell about yourself</h1>
</div>
<br>
<form class="login-card-form">
<div class="form-item">
<input type="text" placeholder="Name" id="text1"
autofocus required>
</div>
<div class="form-item">
<span class="form-item-icon material-symbols-rounded">lock</span>
<input type="text" placeholder="School number" id="text2"
required>
</div>
<button type="submit" id="btn_save">Save</button>
</form>
</div>
</div>
<script>
let btn = document.getElementById('btn_save')
btn.addEventListener('click', function(event) {
//here I need to interact with my DB
})
</script>
That's how I connect to my DB:
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'pocketsage',
password: ''
})
await conn.connect( err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- CONNECTED SUCCESSFULLY')
}
})
await conn.end(err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- DISCONNECTED SUCCESSFULLY')
window.location.href = 'http://localhost:3002/pocketsage'
}
})
}

Cannot POST on JS and MongoDB

I'm very new to web development, and now I'm trying to build a login page which uses HTML, CSS and Javascript for the website, and MongoDB database to store the data received from the user. I followed a few tutorials on YouTube, but for some reasons the data cannot be posted.
Here are the codes that I have so far:
(Javascript)
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded( {extended: true}));
mongoose.connect("mongodb+srv://cs196:cs196#userdata.sn7wv.mongodb.net/cs196", { userNewUrlParser: true}, {useUnifiedTopology: true} );
// create a data schema
const notesSchemaCreate = {
username: String,
email: String,
password: String,
confirm_password: String
}
const Note = mongoose.model("NoteCreate", notesSchemaCreate)
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res) {
let newNote = new Note({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
newNote.save();
})
app.listen(3000, function() {
console.log("server is running on 3000")
})
(And here are the HTML codes)
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<title>Login Site</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<div class="container">
<!-- Create an account -->
<form class="form form--hidden" id="createAccount" method= "post" action="/">
<h1 class="form__title">Create Account</h1>
<div class="form__message form__message--error"></div>
<div class="form__input-group">
<input type="text" id="signupUsername" class="form__input" name="username" autofocus placeholder="Username">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="text" class="form__input" name= "email" autofocus placeholder="Email Address">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "password" autofocus placeholder="Password">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "confirm_password" autofocus placeholder="Confirm Password">
<div class="form__input-error-message"></div>
</div>
<button class="form__button" type="submit">Continue</button>
<p class="form__text">
<a class="form__link" href="./" id="linkLogin">Already have an account? Sign In</a>
</p>
</form>
</div>
</body>
I'm trying out the results using localhost:3000, which looks like this:
The result simply gave me cannot POST / in a new page.
Please let me know if there might be something off with my MongoDB setting, or if you want to see how the setting is right now, since I don't know what parts to show you guys and I don't want to make this post incredibly long.
Thanks in advance for anyone who can help me out with this! And I apologize in advance if my codes or this post is formatted horribly.
Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc).
model.create() is asyncronous. Mark your function as async
So the solution would be:
app.post("/", async(req, res) => {
try {
const newUser = await Note.create({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
res.json({status: "success", message: "user created successfully", user: newUser})
} catch(error) {
res.json({status: "fail", message: error.message ? error.message : "could not create user"})
}
})
P.S: never expose your secret(mongo_uri, stripe_key, etc.) keys public.

enctype="multipart/form-data" always return null input but it is a must for multer to work how can we fix this?

Good day everyone,
I want to use this multer framework for my input which has an image to be uploaded to my project file directory and sending the image file name to mysql database but enctype="multipart/form-data" returns my inputs to null and enctype="multipart/form-data" is a must for multer to work. I can't find relevant issue like mine I need your help guys.
music_index.ejs
<form class="add-music-form" action="/save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="song-featured-image">
<input style="display: none;" type="file" accept="image/*" id="file" name="featured_img" onchange="loadFile(event)" required>
<img id="output" class="image-preview" width="130" src="/img/rock-on.jpg" />
<label for="file" class="attach_file" style="cursor: pointer">
<i class="material-icons">attach_file</i></label>
</div>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a onclick="cancel()" class="btn btn-default">Cancel</a>
</div>
</form>
app.js
app.post('/save', (req, res) => {
upload(req, res, (err) => {
if(err){
res.render('music_index', {
msg: err
});
} else {
if(req.file == undefined){
res.render('music_index', {
msg: 'Error: No File Selected!'
});
} else {
res.render('music_index', {
msg: 'File Uploaded!',
file: `uploads/${req.file.filename}`
});
}
}
});
let data = {
featured_img: req.body.featured_img,
title: req.body.title,
band_name: req.body.band_name,
audio: req.body.audio
};
let sql ="INSERT INTO music SET ?";
let query = connection.query(sql, data,(err, results) => {
if(err) throw err;
res.redirect('/');
});
});
opinion
try req.body-> req.file
let data = {
featured_img: req.file.featured_img,
title: req.file.title,
band_name: req.file.band_name,
audio: req.file.audio
};

Submit form without redirect with node.js

I need to display some loading gif while form submission
but, upon form submit do not refresh the page,
just display a Thank You! message:
Currently, it's refresh the page by submit, and I don't wanted to refresh only display a message after submit.
Here's the code:
/* form hbs */
<form id="myForm" style="display:block" method="POST" role="form" class="form col-md-4 col-md-offset-4 col-xs-12">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name...">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email...">
</div>
<div class="form-group">
<input type="text" class="form-control" id="companyName" name="companyName" placeholder="Your Company Name...">
</div>
<div class="form-group">
<input type="text" class="form-control" id="message" name="message" placeholder="Your Message Here...">
</div>
{{!--onClick="hide();"--}}
<button type="submit" class="btn btn-primary" id="hide">Submit</button>
</form>
//in route index.js
/* GET Add Contact Us page. */
router.get('/ContactUs', function (req, res, next) {
res.render('ContactUs', {
title: 'Contact Us'
});
});
router.post('/ContactUs', function (req, res) {
var name = req.body.name;
var email = req.body.email;
var companyName = req.body.companyName;
var message = req.body.message;
var SQL = "INSERT INTO Contacts(name, email, companyName, message) VALUES($1, $2, $3, $4)";
//send the message to email
handleSayHello(req, res);
query(SQL, [name, email, companyName,message], res, function (json) {
res.render('ContactUs', {
title: 'Success!'
});
});
});
function query(sql, arr, hbsResponse, listener) {
pg.connect(process.env.DATABASE_URL, function (err, client, done) {
if (err) {
return hbsResponse.render('error', {
error: err,
message: err.message
});
}
client.query(sql, arr, function (err, result) {
done(); //close the connection
if (err) {
return hbsResponse.render('error', {
error: err,
message: err.message
});
}
listener(result);
});
});
}
How do I implement it via ajax that post the request without refresh the page and hide form (instead form after submit display another div?
Thank you in advance who that can helping me I will be very grateful!

How can I send data from client to server

I am new to nodejs.please help.
Here is my html and node.js code. I want to send email and password from login.html(client) to login.js(server) and validate from table storing email and password.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://localhost:9383/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
</body>
</html>
login.js
var express = require('express')
, app = express()
, mysql = require("mysql");
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.post('/valid', function (req, res) {
console.log("hello");
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
for (var i in rows) {
console.log('name: ', rows[i].name);
name=rows[i].name;
res.redirect('/option');
}
}
});
connection.end();
});
You're missing a form parsing middleware. Try adding the body-parser middleware somewhere before your POST route.

Categories

Resources