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 >
<p>My Appointments</p>
<hr >
<div >
<div >
<label for="email">email</label><br />
<input type="text" name="email" id="email" required>
</div>
<div >
<input type="submit" value="Search" id="search" >
</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" ><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>
CodePudding user response:
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);
}
})
})