6

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;
    }
}
Nathan Wehr
  • 393
  • 7
  • 15
  • See [ how to return variable from the function called by onreadystatechange=function() ](http://stackoverflow.com/questions/1955248/how-to-return-variable-from-the-function-called-by-onreadystatechangefunction) and [ In AJAX how to retrive variable from inside of onreadystatechange = function () ](http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function). – Matthew Flaschen Sep 17 '10 at 02:23

3 Answers3

5

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
  • 337,827
  • 72
  • 505
  • 443
  • 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 Sep 17 '10 at 02:27
  • @Matthew: Yes, that's a neat idea :) – Daniel Vassallo Sep 17 '10 at 02:29
  • But alert is not the same as return you can alert from within the onreadystatechange, But if you do inside handleResponse `return response` it doesnt return the value to the initial function call. – lisandro Mar 11 '21 at 11:52
0

What about :

function handleResponse (response) {
    return response;
}

which return undefined for synchrounous and asynchronous modes

ZHicham
  • 9
  • 1
0
function getdata(url,callback)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
         var result = xmlhttp.responseText;
         callback(result)
        }
      }
    xmlhttp.open("POST",url,true);
    xmlhttp.send();
}

send a call back function name as second arguement to this function. You can get the response text for that function. simple. But you can't directly return anything from an asynchronous call.

Vignesh
  • 1,045
  • 2
  • 17
  • 34