0
function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } 

So , my problem is very simple but I can not figure it out . I want to access result from the isnewusername function . I am very curious about answer because I spent 1 hour on it . Thank you

2
  • You can't return in that function like that. $.post is asynchronous, the function will return before the call to the server file gets completed. Use an async AJAX call. Commented May 25, 2010 at 4:47
  • This seems to be a common problem. There are many questions related to return value from functions after an asynchronous call is made. I am tagging this with "return-value" to consolidate similar questions. javascript+ajax+return-value is a good enough combination to cover this and all similar questions. Commented May 25, 2010 at 4:58

2 Answers 2

2

It cannot be done the way you're doing it, as ajax queries are asynchronous (meaning, they don't block, and the result will not come instantly, it'll come when the server actually responds). You'll have to call another function with the results (or otherwise, only do something with the results once they are actually available).

For instance:

function isNewUsername(str){ $.post('/api/isnewusername', {username:str}, function(data) { someOtherFunction(data.result); }, "json"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually they can be made synchronous, in which case they do block, but I believe it still can't be done the way the OP wants.
0

As a quick note when you use the jQuery post function you are using a shorthand form of the jQuery ajax function which means you are doing an asynchronous call. Therefore only on a successful response is jQuery going to call your function and put the result from your server side call in the data parameter of your success callback.

To illustrate:

function isNewUsername(str){ $.post('/api/isnewusername', {username:str}, function(data) { alert(data.result); }, "json"); } 

That said you can change your code to specify a synchronous callback but that has the potential to lock the users browser until the request is returned.

3 Comments

has the potential...it does lock the browser
@redsquare True, but the length and pain associated with the lock depends on a variety of factors.
but it always has the potential for the response to never come back....leaving the user to crash out of the browser. I would never use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.