0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't that what I have?: .success(function (data) { returnVal = data; })
move the alert call inside the handler and you'll get what i mean :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.