0

In the following code, it should log the data from the link, but it is logging undefined. I believe the problem may be with the scope, here is my code, thanks.

function getData(link) {
    var string;
    $.get(link, function(data) {
        string = String(data);
    })
    return string;
}
console.log(getData("http://www.industus.com"));
  • You are running into an issue of asynchronous callback - where `return string` is executed before `$.get` returns – karthikr Jul 13 '14 at 02:37
  • This is not a scope issue but an asynchronous issue. Here is the canonical answer : http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – naota Jul 13 '14 at 02:47

2 Answers2

0

You are making an asynchronous request but treating the result asynchronously. Make a synchronous request if you want that, or put the console.log statement inside the success callback function.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • How can I make synchronous? I don't want it to log every time you call the function, only if you use `console.log(getData(link));` – user3786876 Jul 13 '14 at 02:39
  • You can't, you are misunderstanding how asynchronous code works. Considering that console.log() is a debugging statement used during development, you can probably replace the desire to log the result to the console by simply looking at the networking tab in the development tools. –  Jul 13 '14 at 02:48
0

Make it as a synchronous call.

function getData(link) {
  var string;
  $.ajax({
    type:"method_type",
    url: link,
    dataType: "data_type",
    async: false,
    success: function(data){
      string = String(data);
    }
  });
}

If you want to keep it async,

$.get(link, function(data) {
    string = String(data);
    // console.log here 
});
PrashantJ
  • 447
  • 1
  • 3
  • 9
  • Do not use `async: false`. It will do what you expect for your example, but if you leave this code in for production it is more likely to cause user experience problems. Frankly I don't understand why synchronous XHR requests are even allowed. –  Jul 13 '14 at 02:50
  • @Nate, yes, since default behavior is synchronous, `async:false` is unnecessary. And I don't like synchronous calls myself. I just told him both the approaches. – PrashantJ Jul 13 '14 at 02:53