I have made a search bar on the customers page of my website and whatever string the admin enters in the search bar will be sent as a get request, and based on the input I am trying to find all the data in MySQL db which contains the input string inside of the fullname field.
My website build as MVC model, using Express to display data and Node.js
This is my form
<form class="d-flex" method="GET">
<input class="form-control me-2 py-1" type="text" id="search" name="search" placeholder="Search customer name" aria-label="Search" value="<%= %>" />
<button class="btn btn-sm btn-secondary" type="submit">Search</button>
</form>
This is route in web.js file
router.get('/customer?search',authentication.handleAuthentication, authadmin.authAdmin,adminController.searchCustomer);
getCustomerByName() inside adminServices.js
let getCustomerByName = (name) => {
return new Promise(async (resolve, reject) => {
try {
let user = await db.User.find({ fullname: name });
if (user) {
console.log(user);
resolve(user);
} else {
resolve(user);
}
} catch (e) {
reject(e);
}
});
};
searchCustomer() inside adminController.js
let searchCustomer = async (req,res,next) =>{
let name = req.params.search;
let customer = await adminServices.getCustomerByName(name);
return res.render('admin/customer.ejs', {
customer: customer,
});
}
I had tried req.body.search / req.params.search / req.query but seem like it can't get the input.
The URL like this: http://localhost:8080/customer?search=mai
. I couldn't find where is the problem because there is nothing show in the console. Are there any method I could try?
CodePudding user response:
You need to add action
tag to form element. Change route name to just customer
and use req.query.search
in controller.
router.get('/customer', authentication.handleAuthentication, authadmin.authAdmin, adminController.searchCustomer);
let searchCustomer = async(req, res, next) => {
let name = req.query.search; // change params to query
let customer = await adminServices.getCustomerByName(name);
return res.render('admin/customer.ejs', {
customer: customer,
});
}
<form class="d-flex" action="/customer" method="GET">
<input class="form-control me-2 py-1" type="text" id="search" name="search" placeholder="Search customer name" aria-label="Search" value="<%= %>" />
<button class="btn btn-sm btn-secondary" type="submit">Search</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>