I am trying to implement the jQuery autocomplete with a Node REST service but can't get it work.
This my source code:
Autocomplete:
$('#search').autocomplete({
source: function (req, res) {
$.ajax({
url: "http://www.example.com:3000/autocomplete",
dataType: "jsonp",
type: "GET",
data: {
term: req.term
},
success: function (data) {
res($.map(data.results, function (item) {
return {
label: item.id,
value: item.id
};
}));
},
error: function (xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
}
});
Node service:
exports.find = function(req, res) {
var b=req.params.term;
console.log(b);
db.collection('publication', function(err, collection) {
collection.find({type:'pub',content: new RegExp(b, 'i') }).limit(5).toArray(function(err, items) {
res.jsonp(items);
});
});
};
b appears undefined in the console and the autocomplete does not work.
if someone needs it
index.js
var express = require('express'),
autocomplete=require('./routes/autocomplete');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/autocomplete/:search',autocomplete.find);
app.listen(6000);
console.log('Listening on port 3000...');
autocomplete.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('redsocial', server);
db.open(function(err, db) {
if (!err) {
console.log("Connected to 'mydb' database");
db.collection('publication', {strict: true}, function(err, collection) {
if (err) {
console.log("error");
}
});
}
});
exports.find = function(req, res) {
var b=req.params.search;
db.collection('publication', function(err, collection) {
collection.find({type:'pub',content: new RegExp(b,'i')}).limit(5).toArray(function(err, items) {
res.jsonp(items);
});
});
};
jquery
$('#search').autocomplete({
source: function(req,res) {
$.ajax({
url: "http://www.ejemplo.com:3000/autocomplete/"+req.term,
dataType: "jsonp",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.text,//text comes from a collection of mongo
value: item.text
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
select: function(event, ui) {
}
});
Source Code: Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With