For anyone reading this in 2016 and beyond, there is a better way using the request/response
pattern. jQuery autocomplete has a source
option which accepts a function which will receive two arguments when invoked by the plugin: request
and response
. request
is an object containing information about the autocomplete component, namely request.term
which is the value of the input field. response
is a function, accepting a single parameter, the returned data response(data)
. as you can see in my example below, you can use this option to facilitate an ajax request. you can simply pass the request
function as the success callback to jQuery $.ajax
methods and it will work as intended. you could also do other cool stuff using this pattern, like searching in memory if you have already fetched and cached some data, making subsequent searches more real time for users.
$('#term-search').autocomplete({
source: function(request, response) {
$.ajax({
url: $('#api-endpoint').val(),//whether you are using radios, checkboxes, or selects, you can change the endpoint at runtime automatically
dataType: "json",
data: {
query : request.term,//the value of the input is here
language : $('#lang-type').val(), //you can even add extra parameters
token : $('#csrf_token').val()
},
success: response //response is a callable accepting data parameter. no reason to wrap in anonymous function.
});
},
minLength: 1,
cacheLength: 0,
select: function(event, ui) {} //do something with the selected option. refer to jquery ui autocomplete docs for more info
});
availabletags1
andavailabletags2
arrays – Pattychoice1
andchoice2
– Patty