ajaxresponsetext

Returning AJAX responseText as string


In my code I attempt to use AJAX to fetch the content of a template file and return it as a string, which I alert. This results in undefined, however if instead of return xmlhttp.responseText I do alert(xmlhttp.responseText) I get the result I'm after.

Can I return the AJAX content as a string outside the function??

alert(getFile());

function getFile() {

  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function stateChanged() {
    if (xmlhttp.readyState == 4)
      return xmlhttp.responseText;
  }

  xmlhttp.open("POST","/template.html", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send();
}


Solution

  • XMLHttpRequest is async. You should use callback like below

    getFile(alert);
    
    function getFile(callback) {
    
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function stateChanged() {
        if (xmlhttp.readyState == 4)
          callback(xmlhttp.responseText);
      }
    
      xmlhttp.open("POST","/template.html", true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.send();
    }