Search code examples
javascriptjqueryajaxtwitch

Simultaneous Ajax Calls JS Returning Data Incorreclty


I am trying to put strings in an array through two different ajax calls. Divs are then created with ids of the name of string and include data about what twitch streamers are streaming from the ajax requests.

The problem is that I am struggling to do so that the element goes through the first ajax call and then goes through the second because ajax calls are asynchronous. As a result, elements in the array would go through the second ajax request before the first one was completed and try to go into divs that were not yet created.

To try to fix this, I put the second ajax request within the first one like so:

ajax request{

code that makes dis

second ajax request}

This seems to have made the elements in the array come back in the correct order, but the divs are not displaying the data from the ajax requests correctly. I have noticed that when logging the name variable, that only one element in the array seems to get passed through to the second ajax request.

[console log][1]

Anyway, I am still learning how to troubleshoot so any tips would be greatly appreciated.

[This is what it should look like ][2]

Below is the JS and here is a link to the codepen if that is helpful:https://codepen.io/mso122591/pen/jxNoBV

$(document).ready(function() {
  var twichUrl = "https://wind-bow.glitch.me/twitch-api";
  var channels = ["ESL_SC2", "freecodecamp", "OgamingSC2"];
  var name = "";
  var name2 = "";
  var logo = "";

  for (i = 0; i < channels.length; i++) {
    twitchUrl =
      "https://wind-bow.glitch.me/twitch-api/channels/" +
      channels[i] +
      "?callback=?";

    twitchUrlStream =
      "https://wind-bow.glitch.me/twitch-api/streams/" +
      channels[i] +
      "?callback=?";

    $.ajax({
      type: "GET",
      url: twitchUrl,
      dataType: "jsonp",
      jsonp: "callback",
      success: function(data) {
        name = data.display_name;
        logo = data.logo;
        console.log('channel data below:')
        console.log(name);


        $("body").append(
          "<div id=" +
          name +
          "Container>" +
          ' <span class ="icon" id =' +
          name +
          "><img src=" +
          data.logo +
          ">" +
          "</span>" +
          '<span class = "status" id = "' +
          name +
          'data"></span>' +
          "</div>"
        );
        $.ajax({
          type: "GET",
          url: twitchUrlStream,
          dataType: "jsonp",
          jsonp: "callback",
          success: function(data) {
            console.log('stream data below:')

            console.log(name);

            if (data.stream === null) {
              $("#" + name + "data").html( 
                " " + 
                '<a target = "_blank" href ="https://www.twitch.tv/' +
                name +
                '">' +
                name +
                "</a>" +
                " is currently offline"
              );
            } else {
              $("#" + name + "data").html(
                " " +
                '<a target = "_blank" href ="https://www.twitch.tv/' +
                data.stream.channel.display_name +
                '">' +
                data.stream.channel.display_name +
                "</a>" +
                " is Streaming: " +
                data.stream.game +
                "-- " +
                data.stream.channel.status
              );
            }
          }
        });
      }
    });
  }
});

Solution

  • One way of solving this is with promises. I have quickly promisified your jquery with $.when, and have fixed your page.

    There are a few problems with your code. There was a variable not declared with var so it created a global variable, so you always only got the latest http get value.

    I have used the "let" keyword to declare variables and put them inside the for loop. This creates a local variable that is only valid within each loop and is not over written. The for loop uses as a counter variable "i" which also is not declared so this also becomes a global variable.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    https://api.jquery.com/jquery.when/

    $.when(your ajax code)
    

    https://codepen.io/anon/pen/Qrbzqx

    This creates an object with the two responses in the one object. You can now use this to write your HTML to the Document

    notice the .then() these are triggered after each http get