$.getJSON request does not work on button click

Viewed 296

I have tried to find a solution to this problem, I'm currently at a loss. I'm trying to gather info on streams using the twitch API.

I am able to get a .getJSON request to work when I pass in an array of usernames, null is returned if the user is offline or invalid.

$(document).ready(function() {
  var streamers = ["ESL_SC2","OgamingSC2","cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninjas","meteos","c9sneaky","JoshOG"];
  var url = "https://api.twitch.tv/kraken/streams/";
  var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";

  getInitialStreams(streamers, url, cb); //load hard-coded streams
});

function getInitialStreams(streamers, url, cb) {
  //loop through the streamers array to add the initial streams
  for (var i = 0; i < streamers.length; i++) {
    (function(i) {
      $.getJSON(url + streamers[i] + cb, function(data) {
        //If data is returned, the streamer is online
        if (data.stream != null) {
          console.log("online");
        } else {
          console.log("offline");
        }
      });
    })(i);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
      <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
      <button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>

However, when I try to call the API through a click function (eventually pulling any input through the form) .getJSON fails. As seen below.

$(document).ready(function() {
  var url = "https://api.twitch.tv/kraken/streams/";
  var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";

  $("#addStreamerBtn").click(function(e) {
    addStreamer("Ben", url, cb);
  });
});

function addStreamer(streamer, url, cb) {
  console.log("I'm inside the function");
  $.getJSON(url + streamer + cb, function(data) {
    console.log("WE DID IT");
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
  <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
  <button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>

I don't understand why the code won't work for the 2nd snippet. Any guidance would be greatly appreciated.

1 Answers
Related