· 7 years ago · Apr 21, 2018, 10:24 AM
1//Iterate through each channelName and run an ajax call for each one individually.
2
3window.onload = function() {
4 channelNames.forEach(userLogin => {
5
6 $.ajax({
7 type: 'GET',
8 url: url + userLogin,
9 dataType: 'json',
10 headers: {
11 'Client-ID': API_KEY,
12 'Authorization': 'Bearer ' + OAUTH_TOKEN
13 },
14 success: function(dataR) {
15 var loginID, displayName, ProfileIMG;
16 var loginID = dataR.data[0].id;
17 var displayName = dataR.data[0].display_name;
18 var displayIMG = dataR.data[0].profile_image_url;
19 // Collect and store the info needed from this Ajax call then run the function with the required data.
20 streamStatus(loginID, displayName, displayIMG);
21 },
22 error: function () {
23 alert("Something went wrong with your search, please refresh the page and try again");
24 }
25 });
26 });
27
28 // This function runs another ajax call to get the remaining required data. Then builds out the HTML with the required fields.
29 // This CSS and HTML is a little poor quality however the focus on the project was to the API work so focused on that.
30 function streamStatus(loginID, displayName, displayIMG) {
31 $.ajax({
32 type: 'GET',
33 url: url2 + loginID,
34 dataType: 'json',
35 headers: {
36 'Client-ID': API_KEY,
37 'Authorization': 'Bearer ' + OAUTH_TOKEN
38 },
39 success: function(dataR2) {
40 let html = "";
41 var streamMsg = "";
42 var urlLink = "";
43
44 // This checks if the stream is live or not and builds accordingly.
45 if (dataR2.data.length === 0) {
46 html = `<li class="offline"><img class="image" src="${displayIMG}"> <span class="name">${displayName}</span> - "Streamer Currently offline, check back later"</li>`;
47 document.getElementById("insert").innerHTML += html;
48 } else {
49 streamMsg = dataR2.data[0].title;
50 // Following 4 lines builds out the link address for the stream.
51 var begin = dataR2.data[0].thumbnail_url.indexOf('live_user_') + 10;
52 var end = dataR2.data[0].thumbnail_url.lastIndexOf('-{width}');
53 var username = dataR2.data[0].thumbnail_url.slice(begin, end);
54 urlLink = 'https://www.twitch.tv/' + username;
55 html = `<li class="online"><a href="${urlLink}" target="_blank"><img class="image" src="${displayIMG}"></a> <span class="name">${displayName}</span> - "${streamMsg}" </li>`;
56 document.getElementById("insert").innerHTML += html;
57 }
58 },
59 error: function () {
60 alert("Something went wrong with your search, please refresh the page and try again");
61 }
62 });
63 };
64};