-1

I Try using the ajax Asynchronous, but the value just return "undefined". No Jquery please!!

function readTextFile(file){
    if(window.XMLHttpRequest) {
        var rawFile = new XMLHttpRequest();
    }else {
        var rawFile = new ActiveXObject("Microsoft.XMLHTTP");
    }

    rawFile.open("GET", file, false);
    rawFile.send(null);

    //alert(rawFile.responseText);
    var textvalue = rawFile.responseText;
    return textvalue;
}


var str = readTextFile(file);
toastext
  • 325
  • 3
  • 12
  • Check this question and the answer to it: [How can I take advantage of callback functions for asynchronous XMLHttpRequest](http://stackoverflow.com/questions/5485495) – t.niese Mar 25 '16 at 15:26

2 Answers2

1

Please try this solution:

function readTextFile(file) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var textvalue = xhttp.responseText;
    }
  };
  xhttp.open("GET", file, true);
  xhttp.send();
}
kasynych
  • 50
  • 2
1

You need to use onreadystatechange event and a callback:

function readTextFile(file, callback){
    if(window.XMLHttpRequest) {
        var rawFile = new XMLHttpRequest();
    }else {
        var rawFile = new ActiveXObject("Microsoft.XMLHTTP");
    }
    rawFile.onreadystatechange = function() {
        if (rawFilereadyState == 4 && rawFile.status === 200) {
           callback(rawFile.responseText);
        }
    }
    rawFile.open("GET", file, false);
    rawFile.send(null);
}


readTextFile(file, function(str) {
  // use the str
});
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Thanks jcubic, but how does the responseText get return so I can put it in a string?(: and which function do I use. Sorry I'm new to the callback function in ajax and all the guide involve jquery.T^T – toastext Mar 25 '16 at 15:54
  • it's the same as `var str = readTextFile(file)` but the str is inside the callback function as argument, instead of after the readTextFile you put your code inside a callback and use str as argument instead of variable. – jcubic Mar 25 '16 at 16:22