Example: Remote Data via JSONP

This example demonstrates how to provide autocomplete suggestions from a remote JSONP API. In this case, we're using GitHub's user search API to suggest GitHub usernames.

Try typing your GitHub username. If you don't have a GitHub account, try the names of some YUI developers: rgrove, lsmith, davglass, amoore, msweeney


HTML

<div id="demo" class="yui3-skin-sam">
  <label for="ac-input">Enter a GitHub username:</label><br>
  <input id="ac-input" type="text">
</div>

JavaScript

GitHub Response Data

The GitHub Users API returns a JavaScript object that looks like this:

{
  "users": [
    {
      "name": "rgrove",
      "location": "Portland, OR",
      "followers": 55,
      "language": "JavaScript",
      "fullname": "Ryan Grove",
      "username": "rgrove",
      "id": "user-1465",
      "repos": 28,
      "type": "user",
      "pushed": "2010-11-06T00:15:08.327Z",
      "score": 4.8103123,
      "record": null,
      "created": "2008-02-28T07:08:51Z"
    },

    ...
  ]
}

If the response were a simple array of strings, AutoComplete would interpret it correctly by default. However, in this case, the response is an object that contains a users property, the value of which is an array of result objects rather than an array of strings.

This means we'll need to specify a resultListLocator to indicate the property on the response object that contains the array of results, and a resultTextLocator to indicate the property on each result object that contains the suggestion text, as demonstrated in the implementation code below.

Implementation

YUI().use('autocomplete', 'autocomplete-highlighters', function (Y) {
  Y.one('#ac-input').plug(Y.Plugin.AutoComplete, {
    resultHighlighter: 'phraseMatch',
    resultListLocator: 'users',
    resultTextLocator: 'username',
    source: 'http://github.com/api/v2/json/user/search/{query}?callback={callback}'
  });
});

Complete Example Source

<div id="demo" class="yui3-skin-sam">
  <label for="ac-input">Enter a GitHub username:</label><br>
  <input id="ac-input" type="text">
</div>

<script>
YUI().use('autocomplete', 'autocomplete-highlighters', function (Y) {
  Y.one('#ac-input').plug(Y.Plugin.AutoComplete, {
    resultHighlighter: 'phraseMatch',
    resultListLocator: 'users',
    resultTextLocator: 'username',
    source: 'http://github.com/api/v2/json/user/search/{query}?callback={callback}'
  });
});
</script>