0

Hi I am trying to get a return value from a get function from a jquery Get request on success.

I have tried many ways already but with no success. Two forms which i have tries are:

1)

GetResultOutput = function () {
    var outPut = "No Data Found";
    var test = test();
    return test["outPut"];
}

test = function()
{
    outPut = "No Data Found";
    **return** $.ajax({
        type: "GET",
        url: serviceUrl,
        dataType: "xml",
        success: function (xml) {
                    outPut = "done";
        }
    });
}

2)

GetResultOutput = function () {
    outPut = "No Data Found";
    $.ajax({
        type: "GET",
        url: serviceUrl,
        dataType: "xml",
        success: function (xml) {
            outPut = "done";
        }
    });
    return outPut;
}

But both of them is not giving me any result..

2nd one outputs me as no data found. and 1st one which is preferred one when googled...results as undefined

1
  • If you want this call synchronous, then AJAX is the wrong tool for the job! Commented Oct 29, 2012 at 10:30

3 Answers 3

1

Instead of trying to get the output and then process it like:

var output = GetResultOutput();
process(output);

You could pass process as a callback like:

var GetResultOutput = function (callback) {
    $.ajax({
        type: "GET",
        url: serviceUrl,
        dataType: "xml",
        success: function (xml) {
            callback(xml);
        }
    });
};

// usage:
GetResultOutput(process);
Sign up to request clarification or add additional context in comments.

Comments

0

You can also make your ajax call synchronous by using:

   $.ajax({
        type: "GET",
        url: serviceUrl,
        async: false,
        dataType: "xml",
        success: function (xml) {
            outPut = "done";
        }
    });

2 Comments

You can, but it makes the browser lockup while its doing the request - kinda negates the purpose of ajax in the first place.
thats true..it may happen...so u recommend the below fn u provided..because that way when i tried i was getting errors
0

Ajax request are asynchronous, which means you cannot immediately "return" data from the call. That is why all forms of $.ajax take one or more callbacks to be called when data is received, or an error occurs etc.

Which means your method must look like:

GetResultOutput = function (callback) {
   $.ajax({
        type: "GET",
        url: serviceUrl,
        dataType: "xml",
        success: callback
    });
}

with callback looking like:

function callback(xml)
{
   console.log('done: ' + xml);
}

1 Comment

tnx Jamiec, i better used making it async

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.