Reputation: 415
I have this piece of code:
function CallAPI(paramString) {
var returnVal;
var jqxhr = $.get(
"http://url/../"
)
.success(function (data) { returnVal = data; })
.error(function (xhr, ajaxOptions, thrownError) { alert("Error!\n xhr.status = [" + xhr.status + "]\n xhr.statusText: [" + xhr.statusText + "]\najaxOptions = [" + ajaxOptions + "]"); })
.complete(function () { alert("Request complete."); });
alert("returnVal: [" + returnVal+ "]");
}
The "returnVal" in the last alert is returned as "undefined", but when i debug with Firebug, I see the request response is either "true" or "false". The value is send back from the request as pure string, not specific format (JSON, HTML, ..)
Why does "returnVal" not return the request's response value? Thanks
Upvotes: 0
Views: 2853
Reputation: 2860
Because you use it outside the ajax call and, as ajax calls are asynchronous, the alert pops up faster than you get the response. You have to use the returnVal
variable inside the success
handler, to be sure that you get the value returned by the response.
Upvotes: 1