0
function getUsername() {
    $.get("http://www.roblox.com/mobileapi/userinfo", function(data) {
        return data.UserName;
    });
}

console.log(getUsername());

It says "undefined" but whenever I visit the link manually it shows

{"UserID":74798521,"UserName":"AbstractMadness","RobuxBalance":7024,"TicketsBalance":21530,"ThumbnailUrl":"http://t2.rbxcdn.com/c189198f6c0689ce004d9438c70eb1bb","IsAnyBuildersClubMember":true}

It will also log the name if I do console.log(data.UserName) inside of the function.

  • `$.get` is asynchronous. When you call `console.log(getUsername());` it doesn't know what to output. – Andrew Brooke Jan 30 '16 at 23:32
  • $.get is an asynchronously function call. That meas it cannot return a value. You can either set the returned value to a global variable or you can trigger an event. – Fiete Jan 30 '16 at 23:32
  • Your return statement is inside the anonymous callback function, not returning a value from your `getUserName()` function. – nnnnnn Jan 30 '16 at 23:33
  • I think this is because all AJAX calls are async now. So you need to use the callback for when the correct answer is returned. I think it is the .done() function but can't recall it off of the top of my head. – Mark Manning Jan 30 '16 at 23:33

2 Answers2

0

It's not synchronous. You are printing the return of that function, which doesn't return anything (so it's undefined). Even if you were to return the $.get call you wouldn't get what you're looking for. You need to log inside of the callback function or use a promise.

function getUsername() {
    return $.get("http://www.roblox.com/mobileapi/userinfo", function(data) {
        console.log(data.UserName);
        return data.UserName;
    });
}

getUsername().done(function(username) { console.log(username); });
micah
  • 7,596
  • 10
  • 49
  • 90
0

Function getUsername executes a $.getrequest, but it returns nothing and it ends here.

You have to log your data in the function of your asynchronous $.get request. This function (function(data)) is a callback function. It will be called, if the response of your $.get request arrive.

guitarman
  • 3,290
  • 1
  • 17
  • 27