Skip to content
Advertisement

JavaScript getting txt file info not working, no errors

I’m using the code bellow to store everything in a text file into a JavaScript var which than will go into a html id and it will be displayed.

var client = new XMLHttpRequest();
client.open('GET', '/old.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();
window.onload = function(){
    var lengthOfName = client.length

    document.getElementById('output').innerHTML = lengthOfName;
};

but the output id will show nothing in html.

Can anyone help me with this please?

Advertisement

Answer

window.onload doesn’t wait for the AJAX to complete. You should put the AJAX code inside the onload function, and assign to innerHTML inside the onreadystatechange function.

Also, client.length makes no sense. client is the XHR object, not an array or string, it doesn’t have a length. I think you want client.responseText.length.

window.onload = function() {
  var client = new XMLHttpRequest();
  client.open('GET', '/old.txt');
  client.onreadystatechange = function() {
    alert(client.responseText);
    var lengthOfName = client.responseText.length

    document.getElementById('output').innerHTML = lengthOfName;
  }
  client.send();
};
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement