0

What I want is really simple: I've got a javascript server and an HTML client, and I just want to get a string from the server which the HTML page then adds to one of its dropdown menus. There are three relevant blocks of code:

function stringLoader(){
  var xhr = new XMLHttpRequest();
  var url = "/pathname";

  xhr.open("GET",url);

  xhr.setRequestHeader("Content-Type", "text/xml");

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var data = xhr.responseText;
      }
    }
  };
  xhr.send();

  return data;
  }

function loaderCaller(){
  var element = document.getElementById("Menu");
  //"Menu" is the html <select> box I want to add to
  var option = document.createElement("option");
  option.text = stringLoader();
  element.add(option);
  }

These two are in script tags in the client. The relevant code in my server is this:

function handleRequest(req, res) {
//process the request
console.log("Request for: "+req.url);
var filename = ROOT + req.url;
var urlObj = url.parse(req.url, true);


var code = 200;
var data = "";

if(req.method === 'GET' && urlObj.pathname === ("/pathname")){
  res.writeHead(code, {'content-type': 'text/html'});
  res.send("test");
}

I know loaderCaller() will add the option if I set stringLoader to return a string literal instead of a variable, so the problem isn't with that. I also know the if{} in the server is executing, because I've put several console.log() calls to test it.

This should add an option to the select menu that just says "test", right? I assume this is one of those problems where the answer is blindingly obvious. Please help me. This code has been non-functional for many hours and I very much want to die.

1 Answers1

1

data is being returned before the xhr request completes. You can get around this by returning it to a callback function.

function stringLoader(callback){
  var xhr = new XMLHttpRequest();
  var url = "/pathname";

  xhr.open("GET",url);

  xhr.setRequestHeader("Content-Type", "text/xml");

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
          var data = xhr.responseText;
          callback(data);
      }
    }
  };
  xhr.send();
}

function loaderCaller(){
    var element = document.getElementById("Menu");
    var option = document.createElement("option");
    stringLoader(function(data) {
        option.text = data;
        element.add(option);
    });
}
tklg
  • 2,572
  • 2
  • 19
  • 24