I am trying to add a product search functionality in my Node.js web shop project. I am using Express framework with MongoDB/mongoose. My idea is to load index page whenever a user clicks search icon (anchor HTML element), and in my router.get get all products from the database which titles match the user input.
Can someone tell me how to send that data to the server and retrieve it from req?
Relevant code from index.js:
router.get('/', function(req, res, next) {
Product.find({ title: new RegExp(req.data) }, function(err, docs){
var chunks = []; //rows in HTML page
var chunkSize = 3; //No. of elemens in each row
for (var i = 0; i < docs.length; i += chunkSize) {
chunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products : chunks });
});
});
Relevant code from header.hbs:
<ul class="nav navbar-nav navbar-right">
<li>
<form class="navbar-form navbar-left" role="search" id="search-input">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<a href="/" class="btn btn-default"><i class="fa fa-search" aria-hidden="true"></i></a>
</form>
</li>
Is there a way to pass that input's data, say, something like this:
href ="/:search-input.val"
I know that is nonsense, but you should get what I'm aiming at... Any help would be much appreciated as I can't solve this for hours, nor find the answer here.
[EDIT] So, I added a jQuery handler in header.hbs, but it does nothing even though the Chrome console says that XHR request was successful. Any ides?
$('#search-btn').click(function() {
var title = $('#search-input').val();
$.ajax({
type : 'GET',
url: '?title=' + title,
data : title
});
});