-2

In script-a.js I have this function:

function callGetAjax(url,callback) {
       $.get(url, {}, function(result) {
           // this will call the callback and pass the result
           callback(result); 
       });
}

In script-b.js I call it:

var url = '/feed/location';
callGetAjax(url,function(result)
{
    //console.log(result); <= of course this logs right
    data = result;
    return data;
});
console.log(result); // <= ReferenceError: result is not defined
console.log(data); // <= ReferenceError: data is not defined

I don't want make async:false but I need to "export" data to elaborate it. Thank you.

sineverba
  • 5,059
  • 7
  • 39
  • 84
  • It looks like you have no idea how callbacks work. I suggest you read up on that. – Siguza Apr 27 '15 at 13:01
  • 1
    You can not return from an asynchronous method. It is like ordering a pizza online and eating it before it gets to your house. You can not return. All the logic needs to happen when the callback is executed. So you need to break up your logic into parts. Part before and part after. – epascarello Apr 27 '15 at 13:01
  • ok, all clear, thank you @epascarello – sineverba Apr 27 '15 at 13:23

1 Answers1

0

Ajax is an async tool so you can use data only inside it. So, if you need to alter the dom with data you should do it directly:

var url = '/feed/location';
callGetAjax(url,function(result)
{
    //console.log(result); <= of course this logs right
    data = result;
    $('#some_dome_item').html(data);
});
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74