1

My code in my HTML file:

<!doctype html>
<head>
<title>Notes</title>
<script>
function PullNotes() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "notes.txt", true);
txtFile.onreadystatechange = function() {
    if (txtFile.readyState === 4 || txtFile.status == 200) {
        allText = txtFile.responseText;
    }

    document.getElementById('notetext').innerHTML = allText;
}
}
</script>
</head>

<body>
<div id="notetext"><p>Failed.</p></div>
<input type="button" value="Pull Notes" onClick="PullNotes()">
</body>
</html>

When I click the button. Nothing happened.

If you're wondering why it says "Failed" it's so I know that the JavaScript didn't update.

Thanks, ~BN

Brandon Nguyen
  • 345
  • 2
  • 3
  • 15
  • is notes.txt on your file system or on the http server? if you are accessing this html page via http://foo.com/index.html then notes.txt needs to be @ http://foo.com/notes.txt. You also need to `send()` the request I think. – NG. Sep 08 '13 at 22:38
  • Put this in your if-block: `document.getElementById('notetext').innerHTML = allText;` –  Sep 08 '13 at 22:38
  • @SB. Server. I tried it on both local and server. – Brandon Nguyen Sep 08 '13 at 22:41

1 Answers1

0

I believe you need to call txtFile.send() after you assign the onreadystatechange property. Check this out.

Also, notes.txt must be in a sibling location to the html file you are loading. I.e. foo.com/index.html -> foo.com/notes.txt

Your code becomes:

function PullNotes() {
    var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "notes.txt", true);
    txtFile.onreadystatechange = function() {
        if (txtFile.readyState === 4 || txtFile.status == 200) {
            allText = txtFile.responseText;
        }

        document.getElementById('notetext').innerHTML = allText;
    }; // end onreadystatchange prop
    // send the request
    txtFile.send();
}
NG.
  • 22,560
  • 5
  • 55
  • 61