2

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>
8
  • it's necessary to keep that file format? Commented Apr 3, 2015 at 23:37
  • 1
    Will 10 be appended after 9 (...8910)? In that case would the "last value" be 0 or 10? Commented Apr 3, 2015 at 23:39
  • @user2570380 yes 10 will be after 9 then the last value will be 10 Commented Apr 3, 2015 at 23:41
  • So how are you supposed to know how many digits to use at the end? You need to put a delimiter between the values so you can tell. Commented Apr 3, 2015 at 23:42
  • @Typo do you mean the format of how the numbers are displayed like 123? because if so it doesn't matter as long as it follows, so it could also be like 1 2 3 4 5 6 etc. or 1,2,3,4,5,6 etc. as long as the function still gets the last value of the .txt file in this case 6. Commented Apr 3, 2015 at 23:43

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for the answer, before testing the function, I still need to do the delimiter? if so is it just making a comma or space between the numbers?
Yes, you'll need to change the lastChar line to whatever is appropriate for your actual file format.
I have edited my scripts now so it just has to get the value in the text file and not a specific value, can I edit your script in some way to make it work or do I have to do it another way now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.