I am going crazy with .getjson
. I am trying to get data from a Wikipedia API using .getjson
and it works fine. Let's say the Wikipedia API returns 10 selections, and before looping over each selection, I am trying to find the length of array in a for loop. The data is not available yet from the '.getjson'.
Here is my work in codepen. Look at console.log(sp.length);
and sp.length
in the for loop. They should give similar data, but one of them is undefined and other is working fine.
Here is my JS code:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
// console.log(sp.length);
}); //End of getJSON
for (var i=0;i<sp.length;i++){
}
});//End of get ready
Why does console.log
give two different answers even though they both refer to the same variable? One is undefined and the other is working fine.
I edited the question so that it only reflect the problem facing.