/    Sign up×
Community /Pin to ProfileBookmark

Accessing variables from within a JQuery get function…

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>[/code]

to post a comment
HTMLJavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJan 01.2020 — This is a common issue. Ajax works asynchronously, that means the request is sent to the server and it takes a short time until the response arrives. Therefore the wordarray is not yet preset when you place the code that accesses it directly after the Ajax call. You have to place it inside the callback function as you already did.

BTW: You better use code tags instead of backticks: `your code her`

I edited your posting accordingly.
×

Success!

Help @stilts77 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...