How to return a value from a function that calls $ .getJSON?

function lookupRemote(searchTerm) { var defaultReturnValue = 1010; var returnValue = defaultReturnValue; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { returnValue = item.libraryOfCongressNumber; }); } }); return returnValue; } 

Why is the returnValue function of this function always equal to the default value set at the beginning of the function and never matches the value obtained from the JSON search?

+6
javascript jquery getjson return-value
source share
3 answers

This is because this callback function(data) {...} ( function(data) {...} ) is launched later when the response is returned ... because it is an asynchronous function. Instead, use the value as soon as you set it, for example:

 function lookupRemote(searchTerm) { var defaultReturnValue = 1010; var returnValue = defaultReturnValue; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { returnValue = item.libraryOfCongressNumber; }); } OtherFunctionThatUsesTheValue(returnValue); }); } 

This should be all asynchronous behavior, start with what you need when you get it ... what happens when the server responds with data.

+11
source share

If you do not want to use the asynchronous function, it is better to use the following:

 function getValue(){ var value= $.ajax({ url: 'http://www.abc.com', async: false }).responseText; return value; } 

This function waits until a value is returned from the server.

+8
source share

The function you pass getJSON is getJSON when the response to the HTTP request arrives , which is not .

The return statement executes before the response, so the variable has not yet been set.

Make your callback function what you need to do with the data. Do not try to return it.

+3
source share

All Articles