Search code examples
javascriptjqueryajaxautocompletejquery-autocomplete

How to implement Autocomplete like Google with dynamic request parameters?


I'm using the jQuery plugin Autocomplete like Google for a form field foo:

$(function() {
    $("#foo").autocomplete({
        minLength: 3,
        limit: 5,
        source : [{
            url:"/my/ajax/controller/foo?data[name]=%QUERY%",
            type:'remote'
        }],  
    });
});

The URI /my/ajax/controller/foo?data[name]=%QUERY% calls the database service (that executes a statement like SELECT * FROM foo WHERE name LIKE %name%), prepaires the data, and provides a simple array like ['qwer', 'asdf', 'yxcv'].

Now I want to add autocomplete to another field (bar). The difference is, that it needs the current value of the foo for filtering, since the target SQL query looks like SELECT * FROM bar WHERE number JOIN foo ON bar.foo_name = foo.name WHERE number LIKE %number% AND foo.name = foo_name. Here is, how I tried to implement it:

$(function() {
    $("#bar").autocomplete({
        minLength: 3,
        limit: 5,
        valueKey:'number',
        source : [{
            url:"/my/ajax/controller/bar?data[number]=%QUERY%&data[foo_name]=" + $('#foo').val(),
            type:'remote'
        }],  
    });
});

But the value of foo is read only one time -- when the page is loaded. That means, the changes and the current value are ignored then. I tried to pass a callback instead of the URL, but it didn't work.

How to get "Autocomplete like Google" working with dynamically changing fields?


Solution

  • $(function() {
        $("#bar").autocomplete({
            minLength: 3,
            limit: 5,
            source : [
                function(q,add){
                    $.getJSON("/my/ajax/controller/bar?data[number]=" + q + "&data[foo_name]=" + $('#foo').val(), function(resp) {
                        add(resp);
                    })
            }],  
        });
    });