JQuery UI autocomplete with JSON from URL

I am using the jQuery user interface autocomplete function. I can get it to work with an example presented using jQuery UI, like this:

var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $("#tags").autocomplete({ source: availableTags }); 

It works without a problem. But I need to use JSON as a data source, which can be obtained as follows: http: //mysite.local/services/suggest.ashx? Query = ball

If I go to this URL, I will return the JSON as follows:

  [{"id":12,"phrase":"Ball"},{"id":16,"phrase":"Football"},{"id":17,"phrase":"Softball"}] 

How to use a URL as a data source?

I tried to change the original parameter as follows:

 $("#tags").autocomplete({ source: "http://mysite.local/services/suggest.ashx" }); 

But that does not help. I believe that the service does not know which keyword was entered in the input field or so?

Any pointers would be great.

+8
source share
2 answers

You need to change the source to meet the following specifications (described in the documentation for the widget). The source must be an array containing (or returning an array):

  • Simple lines or:
  • objects containing the label property, the value property, or both.

If for some reason you cannot change what your remote source returns, you can convert the data after it has been successfully restored. Here's how you do it:

 $("#tags").autocomplete({ source: function (request, response) { $.ajax({ url: "http://mysite.local/services/suggest.ashx", data: { query: request.term }, success: function (data) { var transformed = $.map(data, function (el) { return { label: el.phrase, id: el.id }; }); response(transformed); }, error: function () { response([]); } }); }); }); 

As you can see, you need to make the AJAX call itself by passing the function to the source function of the widget.

The idea is to use $.map to convert your array to an array containing elements that the autocomplete widget can handle.

Also note that the data parameter passed to the AJAX call must end with ?query=<term> when the user enters the term.

+12
source

Fine! That was almost what I was looking for. I adapted the Andrew code above for a simple JSON list format [item1, item2, ..., itemN]. And it works! http://jsfiddle.net/2ao5spfk/

 $("#tags").autocomplete({ source: function (request, response) { $.ajax({ url: "https://api.fillaware.com/v1/suggest/companies?key=iSkwEtRMxzOFzWwoy8GEvsL7DMlpn94Uffrg8ETYMOlrsspEZI7Ck_ElqvevdIxz", data: { q: request.term }, success: function (data) { var transformed = $.map(data, function (el) { return { label: el }; }); response(transformed); }, error: function () { response([]); } }); } }); 
-one
source

All Articles