Why will my table not display when search button is clicked? - javascript

I can not get the table to display when the search button is clicked using JavaScript. not sure why, can someone please help? Code snippets below and actual repos and site linked below as well.
Here is GitHub repo so that you can see the entire site if you wish:
https://github.com/Chad1515/pets-r-us
Here is the site deployed on heroku:
https://oneal-pets-r-us.herokuapp.com/
//trying to display appointments on my appointment page
app.get('/my-appointments', (req, res) => {
res.render('my-appointments', {
title: 'My Appointments',
})
})
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
res.json(Appointment);
}
})
})
<!--form inputs and card for appointments-->
<section>
<div class="card2">
<p>My Appointments</p>
<hr class="third">
<div class="form">
<div class="form-field">
<label for="email">email</label><br />
<input type="text" class="input" name="email" id="email" required>
</div>
<div class="form-field">
<input type="submit" value="Search" id="search" class="btn">
</div>
<div id="appointments"></div>
</div>
</div>
</section>
<script>
document.getElementById('search').onclick = function() {
const email = document.getElementById('email').value;
fetch('/api/appointments/' + email)
.then(res => res.json())
.then(data => {
let tableString = `<br /><br /><h4 style="font-size: 32px; text-align: center; padding-bottom: 10px;">
My Appointments</h4><table id="appointments" class="table"><tr><th>First name</th><th>Last name</th><th>Email</th><th>Service</th></tr>`;
for (let appointment of data) {
tableString += `<tr><td>${appointment.firstName}</td><td>${appointment.lastName}</td><td>${appointment.email}</td><td>${appointment.service}</td></tr>`;
}
tableString += `</table>`;
document.getElementById('appointments').innerHTML = tableString;
});
}
</script>

It looks like you are responding with the Appointment model object instead of the appointments documents. Try this instead:
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
// Respond with the appointments documents instead of the Appointment model
res.json(appointments);
}
})
})

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'
}
})
}

how to submit the values of one form to other form on submit

Handlebar templete is used as views and nodejs is used in backend. i want to save detail in backend on submit of second form.
{{> alertmessage}}
Website Name*
Check Availability
</form>
<form class="form-horizontal" action="/institute/create" method="POST">
<div class="form-group">
<label for="fullname" class="col-sm-2 control-label">Institute Name*</label>
<div class="col-sm-10">
<div class="form-line">
<input type="text" class="form-control" id="institute_name" name="institute_name"
placeholder="institute_name" value="{{institute.institute_name}}" required>
</div>
</div>
</div>
<div class="form-group">
div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn btn-warning" href="/adminusers">Go to adminusers</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
instituteRouter.post('/checkSubdomainAvailability', async (req, res) => {
let { success, error, validationError } = req.session;
institute_subdomain = req.body.institute_subdomain;
const response = await institute.findOne({ institute_subdomain: institute_subdomain }).exec();
if (response === null) {
console.log('response.institute_subdomain');
req.session.success = 'Subdomain is available.'
req.session.error = null;
return res.redirect("/institute/create");
}
else {
req.session.error = 'Subdomain is taken. Please try again.'
req.session.success = null;
return res.redirect("back");
}
})
instituteRouter.post('/create', async (req, res) => {
let { success, error, validationError } = req.session;
check('owner', 'Please select owner.').notEmpty();
let institute_subdomain = req.body.institute_subdomain;
let { institute_name } = req.body;
let pageToCreate = {
institute_name, institute_subdomain
};
let createdPage = await institute.create(pageToCreate);
if (createdPage) {
req.session.success = 'Institute created successfully.'
return res.redirect('/institute');
}
else {
req.session.error = 'Error occurred in creating a new page';
return res.redirect('/institute');
}
})

MailGun ERROR: TypeError: Cannot read property 'id' of undefined

I'm getting an error when trying to send mail from my website I followed a tutorial on youtube.
Error occurs in index.js which is not even on my server at result.id:
callback(null, { ...result, messageId: result.id });
} catch (error) {
callback(error);
}
};
Here is some of my code server.js:
// email, subject, text
app.post('/email', (req, res) => {
const { subject, email, text } = req.body;
log('Data: ', req.body);
sendMail(email, subject, text, function(err, data) {
if (err) {
log('ERROR: ', err);
return res.status(500).json({ message: err.message || 'Internal Error' });
}
log('Email sent!!!');
return res.json({ message: 'Email sent!!!!!' });
});
});
// Render home page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
// Error page
app.get('/error', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'error.html'));
});
// Email sent page
app.get('/email/sent', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'emailMessage.html'));
});
// Start server
app.get('/',(req, res) =>{
res.sendFile(path.join(__dirname, 'views', 'contact.html'));
});
Here is contact.html:
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="subject" placeholder="Subject" /> <br />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" /> <br />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea name="text" class="form-control" id="text" cols="30" rows="10"></textarea> <br />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="submit" value="Send Message" class="btn btn-primary"
</div>
Please help in anyway you can this is the last step of the website as you can see it was done in node.js. I searched previous answers and was not able to find one that matched what I'm going through. I can't change the index.js file because it's not on my server.

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
};

Issue with updating a document in MongoDB

I'm finding problem in updating the documents which are inserted into the DB.
I have created a web page where I can insert the document into the DB and retrieve and display it on the same page. However, I'm not able to update the existing document.
When I try update the document using the objectID, the data is not getting updated.
I would like help or suggestions on what to do.
FYI: the DB I have used here is 'iot' and the collection is : 'metadata'
I'm a beginner in JS and MongoDB.
I would kindly need some help with this.
var express = require('express');
var router = express.Router();
var assert = require('assert');
var url = "mongodb://localhost:27017";
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
const dbName = 'iot';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/get-data', function(req, res, next){
var resultArray = [];
MongoClient.connect(url, function(err, client){
assert.equal(null, err);
const db = client.db(dbName);
var cursor = db.collection('metadata').find();
cursor.forEach(function(doc, err) {
assert.equal(null, err);
resultArray.push(doc);
}, function(){
client.close();
res.render('index', {items: resultArray});
});
});
});
router.post('/insert', function(req, res, next) {
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
}
MongoClient.connect(url, function(err, client){
assert.equal(null, err);
const db = client.db(dbName);
db.collection('metadata').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('Item inserted');
client.close();
});
});
res.redirect('/');
});
router.post('/update', function(req, res, next) {
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
};
var id = req.body.id;
MongoClient.connect(url, function(err, client){
assert.equal(null, err);
const db = client.db(dbName);
db.collection('metadata').updateOne({"_id": objectId(id)}, {$set: item}, function(err, result) {
assert.equal(null, err);
console.log('Item updated');
db.close();
});
});
///res.redirect('/');
});
router.post('/delete', function(req, res, next) {
var id = req.body.id;
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('metadata').deleteOne({"_id": objectId(id)}, function(err, result) {
assert.equal(null, err);
console.log('Item deleted');
db.close();
});
});
});
module.exports = router;
<h1>HOME DASHBOARD </h1>
<section class="insert">
<h3>Insert Data</h3>
<form action="/insert" method="post">
<div class="input">
<label for="title">Title</label>
<input type="text" id="title" name="title">
</div>
<div class="input">
<label for="content">Content</label>
<input type="text" id="content" name="content">
</div>
<div class="input">
<label for="author">Author</label>
<input type="text" id="author" name="author">
</div>
<button type="submit">INSERT</button>
</form>
</section>
<section class="get">
<h3>Get Data</h3>
LOAD DATA
<div class="gfg">
<div>
{{# each items }}
<article class="item">
<div>Title: {{ this.title }}</div>
<div>Content: {{ this.content }}</div>
<div>Author: {{ this.author }}</div>
<div>ID: {{ this._id }}</div>
</article>
{{/each}}
</div>
</div>
</section>
<section class="update">
<h3>Update Data</h3>
<form action="/update" method="post">
<div class="input">
<label for="id">ID</label>
<input type="text" id="id" name="id">
</div>
<div class="input">
<label for="title">Title</label>
<input type="text" id="title" name="title">
</div>
<div class="input">
<label for="content">Content</label>
<input type="text" id="content" name="content">
</div>
<div class="input">
<label for="author">Author</label>
<input type="text" id="author" name="author">
</div>
<button type="submit">UPDATE</button>
</form>
</section>
</section>
<section class="delete">
<h3>Delete Data</h3>
<form action="/delete" method="post">
<div class="input">
<label for="id">ID</label>
<input type="text" id="id" name="id">
</div>
<button type="submit">DELETE</button>
</form>
</section>
try importing the ObjectID , i don't see it there
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, {useUnifiedTopology: true});
var ObjectID = require('mongodb').ObjectID;
// In your request
{ "_id": ObjectID(req.body.id)}, // Filter
//in your code
client.connect(function(err, client){
assert.equal(null, err);
const db = client.db(dbName);
db.collection('metadata').updateOne({ "_id": ObjectID(req.body.id)}, {$set: item}, function(err, result) {
assert.equal(null, err);
console.log('Item updated');
db.close();
});
});

Categories

Resources