tags:

views:

52

answers:

1

I guess I am missing something quite fundamental and maybe someone can fill me in. I have used an ajax call from two places. So now I am trying to reuse that call by making the call return a value. It looks something like this:

function getInfo()
{
    $.ajax({
    type: "GET",
    url: "../ajax.aspx?action=getInfo&id=4", 
        dataType: "xml",
    async: false,
    error: function() {
        alert("Something went wrong.");
    }, 
    success: function(xml) {
            // Do some extra work here
 $(xml).find("room").each(function() {
     // Do something based on the xml
 }); 
 // Something else can use this XML so return it too.
            // Why does this return not work???
            return xml;
    } 
});
}

So somewhere else in the script i am calling that function

var xml = getInfo();
// Try do something with it now but it says that it is undefined

and when i say it says it is undefined I am talking about Firebug.

A: 

Turning off the asynchronous functionality is imho not a very good AJAX programming style. You will loose a lot of the advantages of this technology. From the jquery documentation:

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

If you need to do it anyway: $.ajax returns the XMLHTTPRequest object it creates. And your getInfo method should return that as well, so your code should be modified like this:

function getInfo()
{
    return $.ajax({
    type: "GET",
    url: "../ajax.aspx?action=getInfo&id=4", 
        dataType: "xml",
    async: false,
    error: function() {
        alert("Something went wrong.");
    }, 
    success: function(xml) {
            // Do some extra work here
        $(xml).find("room").each(function() {
            // Do something based on the xml
        });     
        // Something else can use this XML so return it too.
            // Why does this return not work???
            return xml;
    } 
}).responseText;
}


var xml = getInfo();
Daff
Yes the async false is not a good idea. That was left there by accident while I was playing with the various options. It is removed now. Thank you :)
uriDium
Hm I fear, that if you turn the async mode on you may not be able to return the response text right after the function call but instead use a callback.
Daff