DevLiv
DevLiv

Reputation: 573

Get value from text file in javascript

I have a javascript variable which I display on my html website, I also have a .txt file which gets a payment value from a .php script. These values are displayed like this 12345 in the .txt file, every amount is raised by 1, so first the .txt file gets 1 then 2 then 3 etc. Now my question is, how do I get the last value from the .txt file and turn my variable value into the value I get, by the last value of the .txt file I mean if the current values in the file is 12345 then the last value is 5, then I want to change the variable in my Javascript to that value 5.

My javascript/html script with the variable and display inside.

<div class="newValue">
        Current value: $<span id="newValueVariable"></span>
</div>

 <script type="text/javascript"> 

        var newValueVariable= 1;
        document.getElementById("newValueVariable").innerHTML = newValueVariable;

</script>

Upvotes: 2

Views: 3139

Answers (1)

Barmar
Barmar

Reputation: 780984

Use AJAX:

var xhr = new XMLHttpRequest;
xhr.open("filename.txt", "GET", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var contents = xhr.responseString;
        // Replace next line with what you actually use to parse the file
        var lastChar = contents.substr(-1, 1);
        document.getElementById("newValueVariable").innerHTML = lastChar;
    }
}
xhr.send();

Upvotes: 2

Related Questions