Reputation: 993
This is the HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="/favbar.png" />
<!-- JavaScript -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#search").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/search",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data.results, function( item ) {
return {
label: item,
value: item
}
}));
}
});
}
});
});
</script>
<script src="/stylesheets/bootstrap/js/bootstrap.min.js"></script>
<!-- CSS -->
<link href="/stylesheets/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="/stylesheets/bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/stylesheets/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
<link type="text/css" href="/stylesheets/bootstrapui/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet" />
</head>
<body>
<input type="text" id="search" class="search-query" placeholder="Search..." />
</head>
</body>
</html>
And this is the node.js code:
app.post('/search', function (req, res){
var regex = new RegExp(req.body.term);
usermodel.aggregate({$match: { user: regex }}, function (err, users){
if (err) throw err;
var names = [];
for (var nam in users) {
names.push(users[nam].user);
}
var result = { results: names }
res.json(result);
});
});
This code doesn't work. I get perfectly the AJAX request, the problem is the Node.js response. I don't know if is the type of the response, or the way I send it. names
in an array with all the results, and I send it like this { result: names }
. Maybe I should send only res.json(result)
. In some examples use a GET request, and I use POST, should I change that?
I use mongodb and mongoose for the database.
How can I do this? Thank's advance!
Upvotes: 1
Views: 10651
Reputation: 759
For autocomplete forms, i would recommend twitter typeahead
. Very simple, easy to use and powerfull.
Some examples in: http://twitter.github.com/typeahead.js/examples/
Documentation and the code in: http://twitter.github.com/typeahead.js
Upvotes: 9