'nodejs express search bar from mySQL
So I'm completely new to this and I'm trying to create a search bar which allows client to search for the product they want. But no products is being shown at the page when I click on submit. Except the link change to something like this: http://localhost:3001/search?name=Laptop. Please feel free to edit my code all u want.
This is my product.js
findProducts: function (name,callback) {
var dbConn = db.getConnection();
dbConn.connect(function (err) {
if (err) {
console.log(err);
return callback(err, null);
} else {
const findproductProductsQuery = "select name, image, productid from product where name LIKE '%" + name + "%' ;";
dbConn.query(findproductProductsQuery, [name], (error, results) => {
dbConn.end();
if (error) {
return callback(error, null);
};
console.log(results);
return callback(null, results);
});
}
});
This is my controller.js
app.get("/search", (req, res) => {
const name = req.query.name;
product.findProducts(name, (error, results) => {
if (error) {
console.log(error);
res.status(500).send();
};
res.status(200).send(results);
});
})
This is my search-products.html
<input type="search" name="name" placeholder="search">
<input type="submit" value="Search">
<div class="container-fluid">
<div id="search-results">
</div>
</div>
my script which is also inside my search-products.html
$("#search-form").submit((event) => {
axios.get(`${baseUrl}/products/`)
.then((response) => {
const products = response.data;
products.forEach((product) => {
$("#search-results").append(`
<a href="/product/${product.productid}">
${product.name}<a/>
`);
});
})
.catch((error) => {
console.log(error);
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
