0

I am unable to return javascript function value :

function GetUserName() {
                var returnUserName;
                $.getJSON('/claims/GetUserName', function (data) {
                    returnUserName = "Test";
                    return false;
                    //callback(returnUserName);
                });
                return returnUserName;
}

I am expecting "Test" as the return value but i am getting "undefined"

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
SmartestVEGA
  • 8,415
  • 26
  • 86
  • 139
  • Why `c#` and `asp.net-mcv` tags? – Soner Gönül Dec 30 '15 at 13:07
  • `getJSON()` will make a asynchronous request – Ramanlfc Dec 30 '15 at 13:08
  • 1
    Ohhh, damn it - the first **A** from the AJAX acronym means **ASYNCHRONOUS**. So please stop trying to return values from functions and start thinking in terms of callbacks. Just forget this `return` keyword. – Darin Dimitrov Dec 30 '15 at 13:08
  • how i can rewrite the code – SmartestVEGA Dec 30 '15 at 13:09
  • Read and digest the information in the duplicate. It's the canonical Q&A for this issue, and the example question almost exactly matches your code here. – James Thorpe Dec 30 '15 at 13:10
  • The question is now closed so can't post an answer. You can read the dupe. But here are a few pointers. Have your `GetUserName` take a parameter that will represent a callback. And then invoke this callback in the AJAX success method. Don't try to return any values from it. – Darin Dimitrov Dec 30 '15 at 13:10
  • @SmartestVEGA: Please refer for know how callback work: http://stackoverflow.com/questions/4818615/using-getjson-with-callback-within-a-javascript-object – AddWeb Solution Pvt Ltd Dec 30 '15 at 13:11
  • @AddWebSolutionPvtLtd That question is about a completely different issue, and should probably itself be closed as a duplicate of [this canonical Q&A for that particular issue](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback). – James Thorpe Dec 30 '15 at 13:12

0 Answers0