3

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.

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What is the flow when a user backspaces on the entered text?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.