Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui autocomplete + websockets implementation

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.

like image 656
kasztelan Avatar asked Mar 24 '26 04:03

kasztelan


1 Answers

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.

like image 150
mmgp Avatar answered Mar 26 '26 17:03

mmgp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!