Array.prototype.pop() Return last element of an Array (Success!)

I’m attempting to remove the last element from an array and return, or write that single element to a specific paragraph. However, I’m at a loss.
If someone could help please, it’d be much appreciated!

Ref: MDN web docs Array.prototype.pop() article, and W3Shcools JavaScript Array Methods article

Using the file “time-log.txt” for example, as such, (which is automatically generated by a lua script);

 TIME: 312.05 
 TIME: 312.07 
 TIME: 312.10    
 TIME: 312.12 
 TIME: 312.14 

html example;

<p id="writeData" class="data">Off-Line</p>
<p id="lastStamp">No Data yet</p>

and the Js example;

var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "time-log.txt", true);
	  
    txtFile.onreadystatechange = function() {
       if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
       if (txtFile.status === 200) {  // Makes sure the file exists.
          // no lines = txtFile.responseText; (The lines of text file are not seperated by a comma.)
          // lines = txtFile.responseText.split("\n"); // Will separate each line of the text file by a by a comma.
	var customTextElement2 = document.getElementById('writeData');
        customTextElement2.innerHTML = txtFile.responseText.split("\n"); // (lines seperated by a comma)
			
	/* This part works well enough as it writes to the #writeDate paragraph each line from the text file,
          seperated by a comma, as to what I think is an array. */
} } };  
txtFile.send(null);

/* Here, I'm attempting to write the last line only from above ("\n") to a seperate paragraph, #lastStamp,
however, I'm failing miserably */

var arrayedData = customTextElement2;
document.getElementById("lastStamp").innerHTML = arrayedData.pop();

So, it the above example, the first paragraph element #write data works as expected. It will write all of the “time-log.txt” data to the paragraph, however, not on a new line (vertically) for each line of the original txt file. Instead it writes the data horizontally, with a comma between each line (line of the txt file), into what I’m assuming is an array (and I could be wrong about it being an array :neutral_face: ).
For example, as this;

TIME: 312.05 ,TIME: 312.07 ,TIME: 312.10 ,TIME: 312.12 ,TIME: 312.14 

However for the second part of the js code, in attempting to write to the #lastStamp paragraph, the result I get in the web console is;

ReferenceError: customTextElement2 is not defined

I’m attempting to set the “var arrayedData” to the arrayed output of what I think is the “var customTextElement2”, with;

var arrayedData = customTextElement2;

However, obliviously, it ain’t happening :frowning_face: . So, am I completely off base?
Any suggestion, please? :slightly_smiling_face:

Partial success…

The first block of js below will import all values of the text file to the paragraph id=writeData, while it is the process of being written to by another application. However, the second js will only return the last value or array of the txt file if is is not being written to.
Can anyone help me with this please?

var txtFile = new XMLHttpRequest();
	txtFile.open("GET", "time-log.txt", true);
	  
	txtFile.onreadystatechange = function() {
		if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
		if (txtFile.status === 200) {  // Makes sure the file exists.
		    // no lines = txtFile.responseText; (The lines of text file are not seperated by a comma.)
		    // lines = txtFile.responseText.split("\n"); // This will separate each line of the text file lines by a comma (or into arrays).
	 var customTextElement2 = document.getElementById('writeData');
	     customTextElement2.innerHTML = txtFile.responseText.split("\n");
			
    /* This part works well enough as it writes to the #writeDate paragraph each line from the text file,
       seperated by a comma, into to what is an array. */
} } };
txtFile.send(null);

var popFile = new XMLHttpRequest();
	popFile.open("GET", "time-log.txt", true);
	  
	popFile.onreadystatechange = function() {
	    if (popFile.readyState === 4) {  // Makes sure the document is ready to parse.
	    if (popFile.status === 200) {  // Makes sure the file exists.
		    // no lines = txtFile.responseText; (The lines of text file are not seperated by a comma.)
		    // lines = txtFile.responseText.split("\n"); // This wil separate each line of the text file lines by a comma (or into arrays).
	 var customTextElement2 = document.getElementById('lastStamp');
	     customTextElement2.innerHTML = popFile.responseText.split("\n").pop(); 
		    // The .pop() will remove the last element from the array and returns that value to the caller.
			
} } };
popFile.send(null);

Here is a working example Importing content from a text file (.txt)

and this is another variation, however, same results…

function dataListener () {
  var splitText = document.getElementById('writeData');
	  splitText.innerHTML = dataFile.responseText.split("\n");
	  console.log(this.responseText); 
};

var dataFile = new XMLHttpRequest();
dataFile.open("GET", "time-log.txt");
dataFile.addEventListener("load", dataListener);
dataFile.send();

// stampListener
function stampListener () {
  var splitText = document.getElementById('lastStamp');
	  splitText.innerHTML = stampFile.responseText.split("\n").pop();
	  console.log(this.responseText); 
};

var stampFile = new XMLHttpRequest();
stampFile.open("GET", "time-log.txt");
stampFile.addEventListener("load", stampListener);
stampFile.send();

Hi @DigitalEngine!

I saw this thread today, and thought I’d whip up a simpler example for you. I also saw a message on my email saying you’d had success, and that your next step was create a version that refreshed every x seconds. I included that as well, although that mesage is no longer here; did you delete it?

anyhow, hope you find this useful:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>XHR log time</title>
    <style>

    </style>
  </head>
  <body>
    <p id="writeData" class="data">Off-Line</p>
    <p id="lastStamp">No Data yet</p>

    <script>

    const fullData = document.getElementById('writeData');
    const lastData = document.getElementById('lastStamp');

    function fetchData() {
      console.log('Fetching updated data.');
      let xhr = new XMLHttpRequest();
      xhr.open("GET", "time-log.txt", true);
      xhr.onload = function() {
        updateDisplay(xhr.response);
      }
      xhr.send();
    }

    function updateDisplay(text) {
      fullData.textContent = text;

      let timeArray = text.split('\n');
      
      // included because some file systems always include a blank line at the end of text files.
      if(timeArray[timeArray.length-1] === '') {
        timeArray.pop();
      }

      lastData.textContent = timeArray[timeArray.length-1];
    }

    setInterval(fetchData, 5000);
    </script>
  </body>
</html>

This assumes a file like this:

TIME: 312.05
TIME: 312.07
TIME: 312.10
TIME: 312.12
TIME: 312.14
TIME: 312.15
1 Like

Thanks Again Chris,
I was premature in calling this learning project a success, I should have edited the title as a Educational Work in Progress (EWIP) :slightly_smiling_face:. However the ability for me to reedit the title seems to have expired :expressionless:
And I probably should have opened this thread under MDN LEARN, instead of just MDN, anyways, I’m still learning…

Yes, I did mention I’d like the code to refresh every so many seconds, thanks for that. Not sure what happened to the message though, I thought it was a reply here.

Your example works as expected! This little piece of javascript would make a really good MDN tutorial in itself (tiny hint). I’m going to study, play, and experiment with it, as I have time :microscope:.
I need to get further along in these css & js tutorials also, I can tell.

(by the way, the below, I would like to see if I can learn how to accomplish this myself, before given an answer, I may ask for a hint though if I’m totally stuck, give me a month, or more or, so .)

Next goal is, I’d like to be able to change how the writeData, lastStamp output values are displayed, for example, I’ve set the lua script to write to the “time-log.txt” file every 6 seconds. As the accumulated time changes to minutes, I like for the values to change as displayed, from seconds, to minutes:seconds, to hours:minutes:seconds format as time accumulates.

Again, thanks. thanks, thanks!!

Heh, I could maybe add it to our XHR docs as an extra example? We already have a fetching data tutorial in the learning area that covers a lot of this stuff quite nicely:

You just need this combined with some of the string techniques covered earlier in the learning area. Or maybe I need to add something. Feedback always welcome!

Next goal is, I’d like to be able to change how the writeData, lastStamp output values are displayed, for example, I’ve set the lua script to write to the “time-log.txt” file every 6 seconds. As the accumulated time changes to minutes, I like for the values to change as displayed, from seconds, to minutes:seconds, to hours:minutes:seconds format as time accumulates.

I’ll leave you to it for now. The trickiest part of this tends to be how to convert a given number of seconds into hours, minutes, and seconds components. This is already on MDN (somewhere!) and there are some good stack overflow answers on how to do this.

For sure, I think it’d be a good extra example!

Cool, added it here: https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started#Simple_timed_XHR_example