0

I have a generic function for retrieving data from an outside source as a GET request. I am able to console.log() the response Text inside the function just fine so I know it's retrieving the intended data but every attempt I have made to return said data to a variable has failed dismally. I'm completely at a loss at this point as to how to proceed. Any pointers would be greatly appreciated.

Also it's worth mentioning, due to platform constraints I'm looking to do this purely in javascript.

function httpGet(file){
  var xmlhttp;
  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        console.log(xmlhttp.responseText);
        return xmlhttp.responseText;
      }
    };
    xmlhttp.open("GET", file, true);
    xmlhttp.send();
}

var test = String("file.txt");
result = httpGet(test);
console.log(result);
David
  • 3
  • 1
  • You're chasing a sasquatch. The reason why you are failing is because it cannot be done. You are getting the value in the callback - you need to use it in the callback (or other functions called from the callback). There are very few exceptions to this (storing a variable for later, then using it if it is available, even if the using code is not directly called by the callback). A more useful question than "how do I return this value" for you is "what do I want to do next with this value". – Amadan Dec 07 '16 at 04:19
  • If it's a generic function, then have it accept a callback: `function httpGet(file, cb)`, and then instead of `return` put `cb(xmlhttp.responseText)`. Call the function as `httpGet(test, function(result) { console.log(result); })`. – Amadan Dec 07 '16 at 04:22

0 Answers0