1

How do I return the object correctly in the following jQuery example:-

function get_stockists() {
    $.getJSON("/stockists/ajax_get_all", function(data) {
        //console.log(data);
    });
}

var stockists = get_stockists();
console.log(stockists);
dfsq
  • 191,768
  • 25
  • 236
  • 258
Zabs
  • 13,852
  • 45
  • 173
  • 297

1 Answers1

7

The best method is not to return, but to use a callback function:

function getStockists(callback) {
    $.getJSON("/stockists/ajax_get_all", callback);
}

getStockists(function(stockists) {
    console.log(stockists);
});
Zabs
  • 13,852
  • 45
  • 173
  • 297
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • As @dfsq writes a callback is the correct way to handle this. There is another way as well, namely setting the async: false property, but this is not recommended because it blocks the UI. http://stackoverflow.com/questions/933713/is-there-a-version-of-getjson-that-doesnt-use-a-call-back – ebaxt Oct 26 '12 at 12:06