0

Why is username undefined? I can be sure that the JSON file format is right.

I need set username as the global variable, is there any way i can workaround this?

var loginProfile = 'link to JSON file';
var username;
$.getJSON(loginProfile, function (data) {
    username = data.USERNAME;
});

alert(username);
Programmer
  • 307
  • 3
  • 17

1 Answers1

0

Because your getJSON is asynchronous, the value is undefined when you put alert. Instead you can use callback or function as below and display. Try this,

var loginProfile = 'link to JSON file';
var username;
$.getJSON(loginProfile, function (data) {
    username = data.USERNAME;
    printUserName(username);
});

function printUserName(name){
  alert(name);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396