sammyb123 sammyb123 - 1 month ago 7
Javascript Question

Why does jQuery.ajax not return JSON in a for loop

I am trying to loop through an array in javaScript with array values passed at the end of an variable called "url" so it can retrieve the corresponding JSON from a site. However it returns {"Error:","Not Found", "Status:", 404, "message"}

for( var b = 0; b<all.length; b++){

$.ajax({
url:url+all[b],
type:'GET',
connectionType:'application/json; charset=utf-8',
async:false,
dataType:'jsonp',
success:function(data){
data = JSON.stringify(data);
alert(data);

}
});
}


if I run it like this it works

for( var b = 0; b<all.length; b++){

$.ajax({
url:url+'sammyb123',
type:'GET',
connectionType:'application/json; charset=utf-8',
async:false,
dataType:'jsonp',
success:function(data){
data = JSON.stringify(data);
alert(data);

}
});
}


& if I test the all[b] seperately it returns the correct value within the array. It does not work only when it gets ran as shown in the first snippet of code. Can anyone help me figure out what I'm doing wrong so I can correct the problem.

the value of url is https://wind-bow.hyperdev.space/twitch-api/streams/
I am building a twitch tv app

Answer

try this, I tried it on my end and it worked. You may have a syntax error in your array declaration.

var all = ["ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var url = 'https://wind-bow.hyperdev.space/twitch-api/streams/';

   for( var b = 0; b<all.length; b++){

    $.ajax({
         url:url+all[b],
         type:'GET',
         connectionType:'application/json; charset=utf-8',
         async:false,
         dataType:'jsonp',
         success:function(data){
         data = JSON.stringify(data);
         alert(data);     

         }
     });
   }