0

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();
}
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Musa Mar 22 '18 at 02:29

2 Answers2

1

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);
charmeleon
  • 2,693
  • 1
  • 20
  • 35
1

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();
}
Wyntau
  • 203
  • 2
  • 11
  • Cool, so rather than alerting the result, how would I return it as a string I can use elsewhere? (also, if I want to pass `"/template.html"` to the function as an argument, how would I do that? – Daniel Williams Mar 22 '18 at 02:01
  • You can only use result in callback. The signature is `getFile(fileName, callback)` like Node.js' function `fs.readFile(file, callback)` – Wyntau Mar 22 '18 at 02:04
  • Ok, so I can't pull the value out of the function at all? – Daniel Williams Mar 22 '18 at 02:12