Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 216
Gareth Avatar asked Nov 17 '10 01:11

Gareth


2 Answers

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.

like image 65
JLavoie Avatar answered Oct 13 '22 22:10

JLavoie


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.

like image 29
Quentin Avatar answered Oct 13 '22 23:10

Quentin