KarelRuzicka
KarelRuzicka

Reputation: 471

Autocomplete field with JSON data from external url (Steam API)

I am working on an input field that is autocompleted with names from this link(steam API):

http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json

or

http://api.steampowered.com/ISteamApps/GetAppList/v0001

I would also like the field to return the id of the game despite the name being insered into it.

So far after browsing the forums I put together this but it doesn't quite work:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $("#tags").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json",
                data: { query: request.term },
                success: function (data) {
                    var transformed = $.map(data, function (el) {
                        return {
                            label: el.appid + " - " + el.name,
                            id: el.appid
                        };
                    });
                    response(transformed);
                },
                error: function () {
                    response([]);
                }
            });
          }
      });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

For the autocomplete part I chose to use jQuery autocomplete function: https://jqueryui.com/autocomplete/ however I am open to other methods.

Edit: Fixed syntax error on line 31 but the code still isn't working.

JSFiddle: https://jsfiddle.net/vxej2L5g/

Upvotes: 0

Views: 633

Answers (2)

brozeph
brozeph

Reputation: 26

There is a syntax error in your Javascript on line 31 (basically you have an extra closing parenthesis and semicolon).

The JSON response for the API you are calling wraps the list of apps.

Upvotes: 0

Nawed Khan
Nawed Khan

Reputation: 4391

In the success block you are assigning a label and id. In the label you have assigned name, and in id the appid. We can modify this to format the label like this:

success: function (data) {
   var transformed = $.map(data, function (el) {
      return {
         label: el.appid + " - " + el.name,
         id: el.appid
      };
   });
   response(transformed);
},

Upvotes: 0

Related Questions