Why doesn't this form submit send the input values as expected? I am using PUG templating and I can return desired result by doing http://localhost:3000/search/searchValue
(searchValue being a search string input on the search box) but I can seem to get it to post the data correctly.
I can return results using http://localhost:3000/search/searchValue
but cant get searchValue to carry through to the controller.
I have tried to edit the controller like this (was returning[object object]) but no luck. What am I missing?
edit I tried in controller to change to string
let query = req.params.q;
query = JSON.stringify(query);
result = {email: query} && {fullName: query};
I also tried to edit const query = req.params.q;
to const query = res.send.q;
which returns JSON repsonse`
and I tried this
const query = req.params.q;
query = JSON.stringify(query);
let result = res.send( query );
result = {email: query} && {fullName: query};
Original Controller
router.get('/search/:q', (req, res) => {
const query = req.params.q;
result = {email: query} && {fullName: query};
console.log(result);
Booking.find(result, (err, docs) => {
if (!err) {
res.render('results', {
viewTitle: 'Search Results',
results: docs,
});
console.log(result);
} else {
console.log('Error finding record :' + err);
}
});
});
layout.pug
form.form-inline.my-2.my-lg-0#searchBox(
method='post'
action='/search/' + result
)
input.form-control.mr-sm-2(type='text', placeholder='Search', aria-label='Search', id='q' name='q' value=''
)
button.btn.btn-outline-success.my-2.my-sm-0(type='submit' id='submit') Search
results
each doc in results
-var id = doc._id;
tr
td
a(data-toggle="popover" title="Users ID" data-content= doc._id
)
b= doc.fullName
td= doc.email
td= doc.mobile
td= doc.city
td
UPDATE
I edited my code to the following which works when manually entering a url like http://localhost:3000/search/myquery
, but now I get http://localhost:3000/search/undefined
and the page is blank with the only query value.
router.get('/search/:q', (req, res) => {
const q = req.params.q;
const result = {$or: [{fullName: {$regex: q}}, {email: {$regex: q}}]};
console.log(result);
Booking.find(result, (err, docs) => {
if (!err) {
res.render('results', {
viewTitle: 'Search Results',
results: docs,
});
res.sendFile('views/results');
console.log(query);
} else {
console.log('Error finding record :' + err);
}
});
});
router.post('/search/:q', function(req, res) {
const q = req.body.q;
res.send(q);
console.log(q);
});
Many thanks in advance!