11
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 from this function alway equal to the default value set at the beginning of the function and never to the value retrieved from the JSON lookup?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Gareth
  • 113
  • 1
  • 1
  • 5
  • See http://stackoverflow.com/questions/3537434/cant-get-correct-return-value-from-an-jquery-ajax-call – Crescent Fresh Nov 17 '10 at 02:55
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi Apr 30 '14 at 21:22

4 Answers4

17

If you don't want to use asynchronous function, better use the following:

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

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

JLavoie
  • 16,678
  • 8
  • 33
  • 39
  • 1
    +1 This works like charm if you need synchronous behaviour out of. It will return JSON into String if don't want to change it to string just do `JSON.parse(value)` – Dev Dec 08 '19 at 10:29
14

This happens because that callback function (function(data) {...}) runs later when the response comes back...because it's an asynchronous function. Instead use the value once you have it set, like this:

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 is the way all asynchronous behavior should be, kick off whatever needs the value once you have it...which is when the server responds with data.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
4

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

The return statement executes before the response, so the variable hasn't yet been set.

Have your callback function do what needs doing with the data. Don't try to return it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1
const getJson = (path) => {
  return new Promise((resolve) => {
    $.getJSON(path, function (data) {
      setTimeout(() => {
        resolve(data);
      }, 1);
    });
  })
}
var result = await getJson('test.json');
console.log(result);
amariwan
  • 11
  • 2