Returning AJAX responseText as string

1.3k views Asked by At

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();
}

2

There are 2 answers

3
Wyntau On BEST ANSWER

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();
}
0
charmeleon On

No: to do what you want, you need to accept a callback in your getFile function and invoke it:

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();
}

getFile(alert);