0

I am working on a Javascript / JQuery project that requires that I get data from another website. I use the following JQuery code to achieve this:

var user = "Bob";
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
  profiles = data;
});
alert(profiles);

For some reason when I run the code I get this Error Message:

Uncaught ReferenceError: profiles is not defined

But when type "profiles" in the google chrome javascript console, I see my target data. What am I doing wrong?

Thanks- Evan

EGE
  • 69
  • 6

1 Answers1

0

Are you in 'use strict' or an es6 module ? it sounds like it

You need to explicitly declare the variable

var user = "Bob";
 // this was not really the problem
var profiles;                       
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
  profiles = data;
   // run your alert here
  alert(profiles); 
});
//this is the problem. The above callback function runs asynchronously, 
// after the data has been fetched which can take some time 

// code from this point on runs synchronously, before the request to the server
// hence 'profiles  is undefined'
alert(profiles); 
andrew
  • 9,313
  • 7
  • 30
  • 61
  • That's Exactly what my problem was. Thanks! – EGE Apr 22 '20 at 03:34
  • This will still alert _"undefined"_ but at least it won't throw an error so, progress I guess – Phil Apr 22 '20 at 03:35
  • Ahh, because your call to `alert(profiles)` happens before the async callback runs. move it inside the callback function immediately after `profiles = data;` – andrew Apr 22 '20 at 03:37