user2216267
user2216267

Reputation: 491

How do I create an auto suggestion from a JSON API response?

Amazon provides an API to get suggestions for the letters entered:

 http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook

will give response:

["facebook",["facebook","facebook login","facebook.com","facebook credits","facebook gift card","facebook app","facebook messenger","facebook for dummies","facebook en español","facebook phone"],[{"nodes":[{"alias":"mobile-apps","name":"Apps for Android"},{"alias":"stripbooks","name":"Books"},{"alias":"textbooks-tradein","name":"Books Trade-in"},{"alias":"digital-text","name":"Kindle Store"}]},{},{},{},{},{},{},{},{},{}],[]]

How do I create auto suggestions from this JSON response using jQuery or PHP?

Upvotes: 3

Views: 2857

Answers (1)

binki
binki

Reputation: 8308

If you can use the jqueryui-autocomplete plugin, then you can set its source option to a a function which mediates between the format that jqueryui-autocomplete needs and the API Amazon provides. The following should be able to handle the JSONP response based on the JSON you are giving as an example. You can see that the API endpoint you provided supports JSONP by adding a callback GET parameter to your example URI. For example, http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook&callback=_ returns the data wrapped in a call to _(). jQuery glosses over this with its dataType: 'jsonp' option. This is necessary to support cross-site requests, since you are unlikely to be serving your site with an origin the same as that of the completion API.

/*
 * Connect all <input class="autocomplete"/> to Amazon completion.
 */
jQuery('input.autocomplete').autocomplete({
  source: function(request, response) {
    jQuery.ajax('http://completion.amazon.com/search/complete', {
      /* Disable cache breaker; potentially improves performance. */
      cache: true,
      data: {
        client: 'amazon-search-ui',
        mkt: 1,
        'search-alias': 'aps',
        q: request.term
      },
      error: function() {
        /*
         * jquery-autocomplete’s documentation states that response()
         * must be called once per autocomplete attempt, regardless
         * of whether or not the background request completed
         * successfully or not.
         */
        response([]);
      },
      success: function(data) {
        /*
         * Amazon returns an array of different types of
         * autocomplete metadata. The second member is a
         * list of terms the user might be trying to type.
         * This list is compatible with jqueryui-autocomplete.
         */
        response(data[1]);
      },
      dataType: 'jsonp'
    });
  }
});

Remember to run this code after the DOM is ready, such as from inside a jQuery(document).ready(function() { statements_here(); });.

Upvotes: 5

Related Questions