Skip to content

Instantly share code, notes, and snippets.

@wpflames
Last active November 30, 2020 11:47
Show Gist options
  • Select an option

  • Save wpflames/174cdec17af3570588341c996d6c49b6 to your computer and use it in GitHub Desktop.

Select an option

Save wpflames/174cdec17af3570588341c996d6c49b6 to your computer and use it in GitHub Desktop.
AJAX request for a TXT file - Write text in a specific div
var btn = document.getElementById('button');
btn.addEventListener('click', loadText);
function loadText(){
//Create XHR Object
var xhr = new XMLHttpRequest();
//OPEN - type, url/file, async
xhr.open('GET', 'sample.txt', true);
xhr.onreadystatechange = function(){
console.log('READYSTATE: ', xhr.readyState);
if(this.readyState == 4 && this.status == 200){
document.getElementById('text').innerHTML = this.responseText;
}else if(this.status == 404){
document.getElementById('text').innerHTML = 'File Not Found';
}
}
xhr.onerror = function(){
console.log('Request Error ...');
}
//Sends request
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment