5

I included locally in javascript a list of commonly used terms, and then I would also like to get json response from the server through ajax response. How can it be done?

var projects = ["apple", "orange"];

$('#search').autocomplete({
    source: projects
});

then append the result from ajax?

3
  • In other words, if a local result doesn't exist, make an AJAX call? Or do you always want to make an AJAX call? Commented Dec 26, 2012 at 20:20
  • Actually in any case make the ajax call, sequentially. In other words, if you have two sources, and you don't do the combination on server side, is there a way to combine the result from the two sources via javascript? Commented Dec 27, 2012 at 17:10
  • Yes, there is. I think I have enough information to post an answer Commented Dec 27, 2012 at 17:26

1 Answer 1

6

The way you would go about this would be to combine the results you get back from the server with the local results array. You can accomplish this by passing a function to the source option of autocomplete:

There are three steps you'll have to perform:

  1. Make the AJAX request and get results from the server.
  2. Filter the local array
  3. Combine the results

This should be pretty simple. Something like this would work:

$("input").autocomplete({
    source: function(request, response) { 
        /* local results: */
        var localResults = $.ui.autocomplete.filter(localArray, request.term);

        /* Remote results: */
        $.ajax({
            /* AJAX options omitted... */
            success: function(data) {
                /* Process remote data using $.map, if necessary, then concatenate local
                 * and remote results. 
                 */
                response(data.concat(localResults));
            }
        });
    }
}); 

I've worked up a full example here: http://jsfiddle.net/FZ4N4/

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

2 Comments

What if you want to show the local results and then append the remote results once they are available?
Well I feel stupid. You just call response() again with the new results.

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.