2

Possible Duplicate:
How to return value from $.getJSON

        function get_url(){
            var returnValue  = null;
            $.getJSON('http://127.0.0.1:1337/?callback=?&command=get_url', "", function(data){
                data = $.parseJSON(data);
                returnValue = data[0].get_url;
                console.log(returnValue); // "not_null"

            }); 
            console.log(returnValue);  // "null"
            return returnValue;
        }

Why function don't return "not_null" ?

Community
  • 1
  • 1
ExyTab
  • 527
  • 3
  • 7
  • 14

1 Answers1

3

The call to $.getJSON is asynchronous and won't have completed before your get_url function has returned. There won't be a value in returnValue to return.

You need to either make the call synchronous by using $.ajax with async:false rather than $.getJSON or handle the return value in an asynchronous manner, modifying the calling logic to not expect it straight away.

$.getJSON

is simply shorthand for a call to $.ajax, so you can do this instead:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  async: false,
  success: callback
});
Steve Morgan
  • 12,978
  • 2
  • 40
  • 49
  • Turn your call to $.getJSON into a call to $.ajax with async:false. The code in your success function will then work. – Steve Morgan Aug 12 '11 at 10:39
  • Don't work. function get_url(){ var returnValue = null; $.ajax({ url: 'http://127.0.0.1:1337/?callback=?&command=get_url', dataType: 'json', async: false, success: function(data){ data = $.parseJSON(data); console.log(data[0].get_url); returnValue = data[0].get_url; } }); console.log(returnValue); return returnValue; } – ExyTab Aug 12 '11 at 10:40