Last active
November 30, 2020 11:47
-
-
Save wpflames/174cdec17af3570588341c996d6c49b6 to your computer and use it in GitHub Desktop.
AJAX request for a TXT file - Write text in a specific div
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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