How do I implement autocomplete using nodejs, sockjs and jquery ui autocomplete feature?
Here's the script part
function DocumentReady() {
$("#movieTitle").autocomplete({
minLength: 3,
source: function() {
var title = $("#movieTitle").val();
sock.send(title);
},
delay: 1000
})
}
$(document).ready(DocumentReady);
var sock = new SockJS('http://localhost:9999/ws');
sock.onopen = function() {
console.log('open');
};
sock.onmessage = function(e) {
console.log('message', e.data);
};
sock.onclose = function() {
console.log('close');
};
I'm sending the data to server and I'm receiving the json response without problems. I don't know what should I put in either autocomplete's source function or onmessage event that would allow me to populate the autocomplete list after receiving the data.
One approach for handling this is by effectively using a queue. When you enter something in this autocomplete widget, queue the search term. When you receive a message from sockjs, dequeue and add the suggestions for the autocomplete.
Here is a basic example for this approach (client only, server is working fine as you mentioned):
$(document).ready(function() {
$("#movieTitle").autocomplete({
source: function(request, response) {
sock.send(request.term);
pending.push(response);
}
});
});
var pending = [];
var sock = new SockJS('http://localhost:9999/ws');
sock.onmessage = function(e) {
var response = pending.shift();
response($.parseJSON(e.data));
};
If you feel there is no need for queueing multiple queries, you can just save the latest "response" param from the source option. Then, in the onmessage handler you take this saved callback and show the received suggestions.
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