-1

Possible Duplicate:
Variable doesn’t get returned JQuery

I'm not sure what the problem could be here, but I am losing the result value, of my JQuery Ajax .get call. (code simplified for problem)

File : SomeJSFile.js

var MyApp = function () {

 this.GetAThing = function(url){

 var result = "";
        $.get(url, function (data) {
            result = data;
            alert(data); // Alert works and 'data' looks great! 
            result = data;
        });
        alert(result); // nothing, no value
        return result; // no good since it has no value
  };

 return this;
};

I am using this file in a basic html page for testing.

Have already read: jQuery async ajax query and returning value problem (scope, closure)

Community
  • 1
  • 1
Rex Whitten
  • 725
  • 1
  • 7
  • 20

2 Answers2

1

Since you are alerting the value of result immediately after sending off the request, which is asynchronous, result still has its old value. The value only changes once the request completes, which is when point the handler is executed.

Here is a timeline of what happens:

  1. result is assigned a value of ""
  2. An AJAX request is sent off to a url
  3. The value of result is alerted (it is still an empty string)
  4. The AJAX request completes
  5. The value of result is set to the response
  6. The value of the response is alerted
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

I think the only way you are going to get that results value out of the inner call is to call the inner function and use its return value in the outer function. Something like this maybe:

var MyApp = function () {
 function getUrl() {
  $.get(url, function (data) {
   result = data;
   alert(data); 
   result = data;
   return result;
  };
 }

 var result = getUrl();
 return result;
}
Persival
  • 9
  • 1