views:

66

answers:

2

Here is part of my Ajax function. For some reason that I cannot figure out, I am able to alert() responseText but not able to return responseText. Can anybody help? I need that value to be used in another function.

http.onreadystatechange = function(){
    if( http.readyState == 4 && http.status == 200 ){
        return http.responseText;
    }
}
+2  A: 

You will not be able to handle the return value that you are returning from your asynchronous callback. You should handle the responseText within the callback directly, or call a helper function to handle the response:

http.onreadystatechange = function () {
    if (http.readyState == 4 && http.status == 200) {
        handleResponse(http.responseText);
    }
}

function handleResponse (response) {
    alert(response);
}
Daniel Vassallo
You can also have the function that sets `http.onreadystatechange` take a callback parameter, and call that. See [this example](http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function/290288#290288).
Matthew Flaschen
@Matthew: Yes, that's a neat idea :)
Daniel Vassallo