What could be the reason for the malfunction of my for loop within my JSON operation?

Hi everyone, I'm new to coding and currently working on a project involving Twitch Viewer on FreeCodeCamp.

I've managed to extract information from the JSON file and display it in my HTML code. However, I'm encountering an issue where I am unable to retrieve the names from my "gamer" array.

I'm puzzled why the for loop is not functioning within the json function. Any insights on this would be greatly appreciated!

Thank you in advance for your assistance!

var gamer = ["OgamingSC2","ESL_SC2"];

for(i=0;i<(2);i++){
  
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[i]+'/?callback=?', function(json) {
  $('.list').append("<b>Name: " + gamer[i] + "</b><br>");
  var logo = json.stream.channel.logo;
  
  $('.list').append("Game: " + json.stream.channel.game + "<br>");
  $('.list').append("Status: " + json.stream.channel.status + "<br>");
  $('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
  console.log(json);
});}
img {
  width: 5em;
  border-radius: 10px;
}
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
  <b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>

Answer №1

When using $.getJson, it is important to remember that it is an asynchronous call. This means that it will only execute after all synchronous operations have been completed. As a result, the for loop runs twice and adds two getJSON callback functions to the function stack.

Due to JavaScript's lexical or functional scope, the variable i persists in the global scope as 2 (as the final i++ has also been executed).

Subsequently, the callback functions are executed one by one from the function stack. However, since the value of i is now 2, the callback functions will only reference gamer[2] which does not exist, resulting in an undefined error.

If you were to add a console.log(i) within your $.getJSON, you would observe that it outputs 2 twice.

Consider trying the following approach:

var gamer = ["OgamingSC2", "ESL_SC2"];
gamer.map(function(gamer) {
 loopIt(gamer);
});

function loopIt(gamer) {

 $.getJSON('https://api.twitch.tv/kraken/streams/' + gamer + '/?callback=?', function(json) {
   $('.list').append("<b>Name: " + gamer + "</b><br>");
   var logo = json.stream.channel.logo;

   $('.list').append("Game: " + json.stream.channel.game + "<br>");
   $('.list').append("Status: " + json.stream.channel.status + "<br>");
   $('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
 });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
  <b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>

Answer №2

It seems like the issue is with the JSON response not being displayed because of the callback=? parameter. When you include a ? in the callback variable, it interprets it as part of the value and doesn't return anything. To fix this, simply use callback= without any additional values. Then, try alerting the JSON variable in the function to see if the value is returned properly. There doesn't appear to be any issues with the loop or the JSON link.

Answer №3

When dealing with server calls in a loop like this, it's advisable to utilize a custom loop mechanism.

Here is an example: https://jsfiddle.net/9fwGdk3L/

    var players = ["Ninja","Shroud"];

     var counter = 0;
     fetchData()

     function fetchData(){
        $.getJSON('https://api.twitch.tv/kraken/streams/'+players[counter]+'/?callback=?', function(data) {
    $('.list').append("<b>Username: " + players[counter] + "</b><br>");
    var avatar = data.stream.channel.logo;

     $('.list').append("Game: " + data.stream.channel.game + "<br>");
     $('.list').append("Status: " + data.stream.channel.status + "<br>');
     $('.list').append("Avatar: " + "<img src=" + avatar + ">" + "<br><br><br>');
      console.log(data);
      counter++
      if(counter < players.length){

        fetchData();
     }

});
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to consolidate my array of objects into a single object with distinct keys

Hey there! I'm looking to showcase the expenses for each category throughout the months of the year. Here's an example: {Month: "January", Food: 610, foodColor: "#063951", Others: 121, othersColor: "#C13018", …} Fo ...

Twice the fetch is triggered

I've implemented a simple JavaScript function that handles fetching a URL and updating the HTML page upon receiving a response. Here's an example of how it works: function postToDatabase(self) { // other code here async function postData() ...

safely sending different form inputs in a Ruby on Rails form

Within this snippet, you'll find a part of a table with a form. Each row has its own submit button, which means users have to click on each one individually. I'm currently working on changing this so there is just one button for submission. < ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Issue with JQueryUI Dialog auto width not accounting for vertical scrollbar

My JQueryUI Dialog has the width property set to 'auto'. Everything functions properly except in situations where the content exceeds the height of the dialog: A vertical scrollbar appears, but it disrupts the layout of the content within the dia ...

What is the best way to measure the loading time of a "Loading Screen" page using Jmeter and Selenium?

Once a file is uploaded to the website, a loading screen appears depending on the file size. I am interested in measuring how long this loading screen remains active. As a novice in jmeter and programming, I'm unsure if there's a more efficient m ...

jqGrid doesn't refresh after making an AJAX request

I'm encountering an issue when trying to refresh a jqgrid. Despite attempting various solutions, I have yet to find one that works. My goal is to refresh the grid after receiving JSON data from the server side. Below is the code snippet showcasing how ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

`Is my JSON contact list missing after running `npm build` in React?`

After creating and deploying my React Web App (NodeJs) online, I noticed that the contact form successfully uploads data to my JSON database using fetch post (localhost:3001). However, when trying to locate the database file after running npm run build i ...

New data received in Akka-Http was processed by converting it to a JSON object

Currently, I am working on completing a POST request by unmarshalling received JSON. I need to update the JSON data before submitting it to a Scala method. val route = (path("createDataSets") & post) { entity(as[DataSetEntity]) { dataSetEntity: Da ...

Extract PHP variable and incorporate it into JavaScript code

After doing some research online, I was unable to find a solution to my issue. Can anyone provide assistance with this problem? I currently have a javascript variable that contains the name of a PHP session address. I am trying to access this session valu ...

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...

Issue with Ajax reload functions malfunctioning

Embarking on a new journey, I am diving headfirst into the world of web development. As an artist and writer, I have recently delved into the realm of creating a project that integrates a cms, project manager, and database front-end using php, mysql, and j ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

Troubleshooting overlap problem between Skrollr and SlickNav

I successfully implemented Skrollr to fix images, similar to this example: Additionally, I am utilizing Slicknav for the menu functionality. However, I encountered an issue where the menu opens behind the fixed "parallax" image. Despite trying various ap ...

Guide to accessing and showcasing an embedded Firestore entity using Angular?

I'm looking to showcase a Firestore model with profile names and hashtags using Angular 6. As I delve into Firestore, I've discovered that the proper way to model it is like this: enter image description here members { id: xyz ...

Efficiently Populating Arrays Without Blocking

Let's dive into the scenario... Here is the template for our component <template> <div> <loader v-show="loading"></loader> // display loading animation <div v-show="!loading"> <div v-for="group in groups ...

Python KeyError: When Attempting to Retrieve JSON Data With an Index of 0

I have encountered an error while using selenium to verify a value in a json request. My approach involves first logging in, as the response is dependent on being logged in. I am attempting to retrieve a user's balance from the json and display it to ...