I have used a jQuery get function to fetch some data from a url.
I can use the information I receive within the function(data) part of the code. I can manipulate the data too (so I can isolate one particular key of information).
As soon as I step outside the function… the variable becomes ‘undefined’. I declared the variables before I call the JQuery get.
What is going on?
[code]<script>
var data, word, datafanque, wordarray=[], i, obj, obj2,wordobj;
// search datamuse to create array of synoynyms for the word
$.get(“https://api.datamuse.com/words?ml=hello&max=10”,function(data){
console.log(data);
obj=data;
console.log(obj[2].word); // me testing to see if I can access the array – which I can
for(i=0;i<10;i++){
wordarray[i]=obj[i].word;
}
console.log(wordarray);// this logs correctly
document.getElementById(“box6”).innerHTML=wordarray; //puts the array in the div – as desired.
});
document.getElementById(“box6”).innerHTML=wordarray; //does not put the array in the div – as desired.
</script>