0

This is makinkg me crazy, i cant Get the outside variable Get the inside data

Sorry for the bad formating I'm writing from the phone, if someone can helpme out with the format I appreciate it

  window.getReasons = function(line) {
    var $reasons;

    $reasons = "";
    $.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line, function(returnData) {
      $reasons = returnData.toString();
      return console.log("T_T ----->" + returnData.toString());
    }, "html");
    console.log($reasons);
    return $reasons;
  };
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
KoU_warch
  • 2,160
  • 1
  • 25
  • 46
  • I don;t know what you mean by the "outside variable" and "inside data" Can you be specific about what you are trying to do? – Mike Brant May 08 '13 at 19:07
  • @EH_warch, look at jbabey's link. $.get is asynchronous, you should never get the correct value to return in getReasons() – Ben May 08 '13 at 19:08
  • this will not work, because you are returning the reason variable before it is set to its new value. Remember that this is an asynchronous call – Ibu May 08 '13 at 19:09

2 Answers2

3

The most important thing for you to understand is that $.get() is ASYNCHRONOUS by default. So what is happening is that your console.log() and return statements that follow your call to get() are executing before the get() has returned it's value.

You might look to utilize the when() method here to handle the deferred object that is returned from get()

window.getReasons = function(line) {
    var reasons = '';
    $.when(
        $.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line)
    ).done(function(jqxhr) {
        data = jqxhr[0];   
        reasons = data.toString();
    });
    console.log(reasons);
    return reasons;
}
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
1

$reasons won't be updated until after the GET completes on the server and the response is returned. But your console.log will execute immediately after the request is made.

jalynn2
  • 6,397
  • 2
  • 16
  • 15