I am trying to make a freeCodeCamp Intermediate Front End Development project which needs me to make use of Twitchtv API.
Currently, this code gives errors. When I analysed it with JSHint, it says that I cannot put a function inside a loop.
Code:
$("document").ready(function() {
var streamers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
var htm = "";
for (i = 0; i < streamers.length; i++) {
var url = "https://wind-bow.gomix.me/twitch-api/channels/" + streamers[i];
console.log(url);
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data) {
console.log("Success!");
console.log(url);
console.log(data);
},
error: function(data) {
console.log("Error!");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now when I remove functions from the loop, it gives an error that data is not defined.
Code:
function myFunction(data) {
console.log("Success!");
console.log(url);
console.log(data);
}
function myFunction2(data = null) {
console.log("Error!");
}
$("document").ready(function() {
var streamers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
var htm = "";
for (i = 0; i < streamers.length; i++) {
var url = "https://wind-bow.gomix.me/twitch-api/channels/ESL_SC2"; //+streamers[i];
console.log(url);
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: myFunction(data),
error: myFunction2(data)
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I got API from here
I want to know how to remove these problems from my code:
See here is a working example for your ajax call
$("document").ready(function() {
var streamers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
for (i = 0; i < streamers.length; i++) {
$.ajax({
url: "https://wind-bow.gomix.me/twitch-api/channels/"+streamers[i],
type: 'GET',
dataType: 'jsonp', // added data type
success: function(res) {
console.log(res);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>