views:

1517

answers:

3

I use prototype to do my AJAX development, and I use the code like this:

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
            }
        }
    });
    return result;
}

And I find that the "result" is an empty string. So, I tried this:

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                return result;
            }
        }
    });

}

But it didn't work also. How can I get the responseText for other method to use?

+2  A: 

remember that onComplete is called long after the someFunction is done working. What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete):

somefunction: function(callback){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                callback(result);
            }
        }
    });

}
somefunction(function(result){
  alert(result);
});
Marius
A: 

How about adding "asynchronous: false" in your code? In my case, it worked well :)

someone
A: 

bravo Marius :) @someone: using asynchronous: false is not a good programming stratergey, it can hang your browser indefinately

rajkumar
This is not an answer. It is a response to two other answer. Please delete this, and add the comments to the corresponding answers.
Peter Ajtai