0

What is wrong with my script? It has a global variable which is later set with a function, but it comes back as undefined. Why is that?

<script>
var userName

function getAnonUserName() {
  $.ajax({
  url: "https://ck:8081/get-username",
  type: "get",
  success: function(response) {
  userName = response
  }
  })
}

window.onload = function() {
 getAnonUserName()
 console.log(userName)
kimaduv
  • 11
  • 1
  • `$.ajax` is asynchronous, so your `console.log()` is called earlier than you get it. – Walk Oct 04 '17 at 11:59
  • function getAnonUserName() { $.ajax({ url: "https://ck:8081/get-username", type: "get", success: function(response) { userName = response } }).done(function(){console.log(userName)}) // try this it will print } – Vinod kumar G Oct 04 '17 at 11:59

1 Answers1

-1

getAnonUserName is asynchronous, you have to wait for the response