0

i have this:

var something = makeRequest(url);

function makeRequest(url) {

  var http_request = false;

  if (window.XMLHttpRequest) {
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) {
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!http_request) {
    console.log('Falla :( No es posible crear una instancia XMLHTTP');
    return false;
  }

  http_request.onreadystatechange = alertContents;
  http_request.open('GET', url, true);
  http_request.send(null);


  function alertContents() {

    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        //console.log(http_request.responseText); //this show a string result
        //return http_request.responseText; //this not return nothing
        //var something = http_request.responseText; // this return a undefined variable
      } else {
        console.log('Hubo problemas con la petición.');
      }
    }
  }
}

look just under "if (http_request.status == 200)" the three things i prove and NOTHING.

i don't know how to get out of the function the result of the call. please help me

R3tep
  • 12,512
  • 10
  • 48
  • 75
Muribury
  • 3
  • 4
  • See [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) and [Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski Jun 10 '15 at 16:31

1 Answers1

0

Your alertContents() function is executed asynchronously. You cannot return a value from the function. You can declare a global variable and assign the reponseText value to it and then process it.

var result ;
function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            result = http_request.responseText ;
            process(result) ; // guaranteed that there will be some response
        }
    }
}

process(result); // Does not guarantee that result will have the 
                 // returned value (response) and may result in failure
a_pradhan
  • 3,285
  • 1
  • 18
  • 23