Executing a pair of AJAX calls and combining their results within a single div element

My project entails utilizing two AJAX requests

The first request loads all the streams

The second request retrieves information about online streams

Due to lack of combined data from APIs for both online and offline streams,

I have successfully loaded all streams with names and logos

If a stream is online, I aim to make changes to the stream div (add status, change background color to green)

This is what I attempted

List of streamers:

var streamer = ["Thulz","ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "habathcx", "RobotCaleb", "noobs2ninjas","Rakin"];

A for loop that fetches each streamer, with the first AJAX fetching each streamer's information and placing them in individual divs, while I struggle with the second part

for(i=0;i<streamer.length;i++){
    $.ajax({
    url: "https://wind-bow.glitch.me/twitch-api/channels/"+streamer[i],
    success: function(response) {

    $("#result").append("<div class='row streams'><div class='col-12 imag'><img src='"+response.logo+"' alt='"+response.name+"' height='75' width='75'><div class='texts'>"+response.name+"<p id='"+response.name+"'></p></div></div></div>");          
}});//first AJAX

    $.ajax({//second ajax
    url: "https://wind-bow.glitch.me/twitch-api/streams/"+streamer[i],
    success: function(online) {
        if(online.stream !== null){
            console.log(online.stream.channel.status);
        }
    }//response success
            });

}//streamer for loop

Attempts made:

I assigned unique #id to each streamer and then appended the status and applied CSS changes to the streamers returned by the second request

$("#"+streamer[i]).append(online.stream.channel.status);

or

var sname= online.stream.channel.name;
$("#"+sname).append(online.stream.channel.status);

However, none of these methods worked. Seeking assistance!

Answer №1

Received an answer to my query at this link.

Here is the solution provided:

The issue you're facing relates to handling asynchronous calls with AJAX. While your code requests data from the API and awaits responses, the loop continues without storing the data upon arrival. To resolve this, store the results of your AJAX calls in variables. Once both variables have successfully retrieved their data, take action:

var a = $.ajax({ . . . }); //first AJAX
var b = $.ajax({ . . . }); //second AJAX

$.when(a, b).done(function(channelData, streamData) { . . . });

Using $.when().done() ensures that the loop waits for both variables before proceeding. Place your append() function within this block to check if it resolves the issue. Remember, channelData and streamData represent a and b respectively; you can use different variable names if preferred.

Final version on CodePen: https://codepen.io/Krimlen/pen/rzejdV

Revised JavaScript code:

var streamer = ["Thulz", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "habathcx", "RobotCaleb", "noobs2ninjas","Rakin"];
for(i=0; i<streamer.length; i++){
var firstAjax = $.ajax({
url: "https://wind-bow.glitch.me/twitch-api/channels/"+streamer[i]});//first AJAX
var secondAjax = $.ajax({//second ajax
url: "https://wind-bow.glitch.me/twitch-api/streams/"+streamer[i]
});
$.when(firstAjax, secondAjax).done(function(channel, live) {

$("#result").append(*combine and display data retrieved from both AJAX calls*);

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

Creating a dropdown menu that includes miniature images: A step-by-step guide

Specifics I am interested in incorporating a small flag to the left of my dropdown menu. I need guidance on the recommended method for achieving this. My Attempt So Far <!-- Dropdown-Menu --> <div class="col-sm-6 drop-down "> S ...

Interface similar to Amazon that allows users to easily choose product size and color by clicking on the desired options (e.g., clicking on a small red box to select a

For my e-commerce website, I am looking to create a user-friendly interface similar to that of Amazon for selecting product size and color. Instead of traditional radio buttons, I want to display a grid of small boxes, each representing a different color o ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

Styling for Print Media: Adjusting the horizontal spacing between inline elements

I have been developing a custom AngularJS point-of-sale (POS) system that requires printing receipts upon completing a sale. To achieve this, I am using ng-print to print out a sales summary displayed within a specific div element after hiding all other un ...

Meteor JS failed to load the CSS file due to an unsupported MIME type

Currently, I am working on a meteor js 1.8 app. I have created a layout and now I want to add CSS to it. Here is the structure I am following: imports -ui --stylesheets --bootstrap.min.css --font-awesome.min.css --skins.css --forms.css All my CSS files ...

Failure of Highchart's resizing mechanism when hidden

Check out this AngularJS demo app featuring Highcharts: http://jsfiddle.net/dennismadsen/dpw8b8vv/1/ <div ng-app="myapp"> <div ng-controller="myctrl"> <button ng-click="hideView()">1. Hide</button> <button ng ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

The modal div remains hidden when embedded inside a PHP file

When I include an agenda.php file that contains a div with the Bootstrap modal class inside another div in a PHP file, it does not display properly. agenda.php <style type="text/css"> .block a:hover{ color: silver; } ...

"Learn the process of customizing the border color of a drop-down menu using

Is there a way to add validation to a drop-down menu so that the border color turns red if an option is not selected? $("#MainContent_ddlSuppliers option:selected'").css("border", "1px solid #F78181"); ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Switch up the display and concealment of div elements with the power of

Looking for a solution to alternate between "cheese" and "wine" divs output to the page with PHP? Take a look at this code: <div class="cheese"></div> <div class="wine"></div> <div class="cheese"></div> <div class="c ...

Notification indicating that an object has been identified

Here is the code I am working with: const username = "john"; const password = "doe"; const url = '//api.bos2.cf/?type=verify&username=' + username + '&password=' + password + '&callback=?'; $.getJSON(url, functi ...

Tips for properly structuring the ajax POST request for basecamp

Creating a message from bash shell using the curl method outlined in the basecamp api docs is a breeze. However, since my application is not in php, I want to be able to interact with the basecamp server via a simple ajax post. Unfortunately, I'm faci ...

Angular 13's APP_INITIALIZER doesn't wait as expected

Recently, I have been in the process of upgrading from okta/okta-angular version 3.x to 5.x and encountered an unexpected bug. Upon startup of the application, we utilized APP_INITIALIZER to trigger appInitializerFactory(configService: ConfigService), whi ...

Removing a specific element from a JSON array by its ID

Our Project Framework: CodeIgniter Within our project, we utilized two tables named "person" and "emailGroups". Individuals were stored in the "person" table along with their respective group IDs in JSON format, as a person can belong to multiple groups. ...

Getting JSON data from an ASP.NET C# server and returning it in a success function

Having trouble retrieving JSON data in this code. Any assistance would be greatly appreciated... JavaScript Code success: function (response) { var obj; try { obj = Ext.JSON.decode(response.response.Text); } catch (error) { ...

Creating a jQuery countdown script

Is it possible to easily convert the function below into jQuery and still maintain the ability to call multiple instances of the countdown? This particular function receives a server time echoed by the server and then initiates a countdown to the specifie ...

Instead of broadcasting your message to the channel, try sending it directly to the user

While attempting to send this embed to a user's DMs instead of a channel, I have encountered numerous outdated and irrelevant posts that do not address my specific question. module.exports = { name: 'help', description: 'this is a ...

Proper method for adding elements in d3.js

I have a block of code that selects an #id and appends a svg-element into it: var graph = d3.select(elemId).append("svg") .attr('width', '100%') .attr('height', '100%') .append('g') Within th ...

After clicking, revert back to the starting position

Hey there, I have a question about manipulating elements in the DOM. Here's the scenario: when I click a button, a div is displayed. After 2 seconds, this div is replaced by another one which has a function attached to it that removes the div again. ...