namzaG
namzaG

Reputation: 582

Passing parameter dynamically to YouTube API using jQuery

I am making a YouTube API request like this:

$.get("https://www.googleapis.com/youtube/v3/channels", {
    part: "contentDetails",
    id: "somestring",
    key: "MY-API-KEY"
} /*, ...*/ )

I have a hidden field with the value id. The user can choose if they want to use id or forUsername.

If I use the jQuery code below I get an error:

unexpected string

and from the API parameter is missing but the value is id in this case.

$.get("https://www.googleapis.com/youtube/v3/channels", {
    part: "contentDetails",
    $("#subtype").val(): $("#url").val(),
    key: "MY-API-KEY"
}, /*, ...*/ )

How can I use the jQuery code?

Upvotes: 0

Views: 132

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272106

You can use the new ES6 object initializer syntax for this:

$.get("https://www.googleapis.com/youtube/v3/channels", {
    part: "contentDetails",
    [$("#subtype").val()]: $("#url").val(),
    key: "MY-API-KEY"
})

Notice the square brackets around computed property name. If you want to support browsers that do not support ES6 then use a simpler approach:

var params = {
    part: "contentDetails",
    key: "MY-API-KEY"
};
params[$("#subtype").val()] = $("#url").val();
$.get("https://www.googleapis.com/youtube/v3/channels", params);

Upvotes: 1

JonathanST
JonathanST

Reputation: 1

You can use promises ES6 object like this.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  username / id:
  <select id="subtype">
    <option value="ForUsername">username</option>
    <option value="id">id</option> 
  </select>
  <br> Last name: <input type="text" id="url"><br>
  <button type="button" id="searchButton">Click Me!</button>
  <script>
    $("#searchButton").click(function() {
      var paramsChooseByUser = $("#subtype").val();
      var paramsValue = $("#url").val();
      $.get("https://www.googleapis.com/youtube/v3/channels", {
          part: "id",
          [paramsChooseByUser]: paramsValue,
          key: 'someValidKey'
        })
        .always(function(data) {
          console.log(data.responseJSON);
        });

    });
  </script>
</body>

</html>

Upvotes: 0

Related Questions