title: Returning the HTTP response in javascript
body: <p>I am using XMLHttpRequest in javascript to make HTTP request to a local server. This is the code I am using.</p>
  
  <pre><code>var xhr = new XMLHttpRequest();
  xhr.open("POST", "//localhost:5000/translate", true); 
  xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
  xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
  xhr.send(JSON.stringify({"sentence":str}));
  
  
  xhr.onreadystatechange = processRequest;
  
  function processRequest(e)
  {
    if (xhr.readyState == 4)
    {
      console.log('trans_res set');
      trans_res = xhr.responseText; // here trans_res is a global variable
      return String(xhr.responseText);
    }
  }
  </code></pre>
  
  <p>I want this function to return the responseText so that I can use it some where else.</p>
  
  <p>For that I tried two methods,
  1) I tried returning the response and printing the response in console</p>
  
  <pre><code>var temp = function(string)
  console.log(temp)
  </code></pre>
  
  <p>but the temp variable is coming as undefined in console, mostly I think it is because before it comes to console.log it is not yet set (response not returned)</p>
  
  <p>2) I put a global variable (trans_res) and set it in the function and print it</p>
  
  <pre><code>var temp = function(string)
  console.log(trans_res)
  </code></pre>
  
  <p>however it is also coming as undefined.</p>
  
  <p>How can i ensure that I return the response, It's all right if i need to halt the execution somewhere in between, but I want a valid response.</p>