• 0

[JS] display text file contents by getting name from "a" element


Question

What I wanted to do was create a text file with a name like 19-06-2009.txt and then have Javascript read the contents to display on another section in the page. I would also like to combine this with an onclick for links on the right of the page. So that the latest news would display on the left by default, but when the user clicked a link on the right it would change the news content.

I was hoping for a simple way of doing it. Something like an onclick event for the "a" element on the right that would read the link's name (which will be the same as the file's name) and use that to grab the file from the site and set the conents to a variable, which will display in the left column. The reason I wanted to try something like this was so that I would only have to change the a tags around instead of doing it all manually and changing the whole page every time there is a new post.

I'm hoping to learn Javascript and figured this would be a good trial and error thing for me.

<html>
<head>
<title>title</title>
<script type="text/javascript">
function getNewsFile () {
XMLHttpRequest something something something... I get lost here.
}
var NewsPost = something something something...
document.getElementById('leftcontent').innerHTML= document.write(NewsPost)
</script>
</head>
<body>
<div id="leftcontent">
</div>
<div id="rightcontent><a href="news/06-19-2009.txt" onclick="getNewsFile()">06-19-2009</a></div>
</body>
</html>

I will control the text files that get uploaded so if it would be easier to add a variable inside the text file that's fine. Just looking for an easy solution here that keeps the page nice and clean. If possible an external .js file I could link to in the head would also be welcome. I'm trying to keep this as xhtml 1.0 strict friendly as possible and don't want any script tags in the body.

7 answers to this question

Recommended Posts

  • 0

You're on the right tracks, you just need to know how to use the XmlHttpRequest object to get what you need. I haven't tested this, but it should work:

var request;

var getXmlHttpRequest = function() {
  if (!window.ActiveXObject) {
	try {
	  return new XMLHttpRequest();
	} catch (e) {
	  return false;
	}
  }

  try {
	return new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
	return false;
  }
};

var displayFile = function() {
  if (request.readyState == 4 && request.status == 200) {
	var element = document.getElementById("leftcontent");
	if (element) {
	  element.innerHtml = request.responseText;
	}
  }
};

var loadFile = function(url) {
  request = getXmlHttpRequest();
  if (request) {
	request.onreadystatechange = displayFile;
	request.open("GET", url, true);
	request.send("");
  }
};

The general idea is, we create an instance of our request object, and simple make a request to it. If the file is returned succesfully (http status 200), we can load the data into the html element.

Interestingly enough, if you started to use a javascript framework like JQuery, you could accomplish the above, with a much much smaller method:

var getFile = function(url) {
  $.get(url, function(result) {
	$("#leftcontent").html(result);
  });
};

  • 0

Okay, so you're creating a variable called "request", then another called "getXmlHttpRequest" whose value is the results of the function performed. The function itself first checks if your browser uses ActiveX Objects, and if not, tries XMLHTTPRequest method, and if it detects ActiveX it tries the Microsoft IE way of doing it via XMLHTTP.

Next you create the variable "displayFile" whose value is the function. This function says that if the readyState of "request" is equal to 4 (I know there is "complete", "interactive", etc. but which number corresponds to which status?) and the server responds with the 200 status then set the variable "element" to the element with the id "leftcontent" and set the innerHTML of this element to the response given by the variable "request" later on.

Finally the variable loadFile performs the function of setting the variable "request" to use the XMLHttpRequest/XMLHTTP method so that if "request"... something readystateChange... to "get" the url (which would be where I use the onclick results to change the request based on the user's click) and then send... send ""?

The only parts I don't understand so far are

catch (e) {
	  return false;
	}

request.onreadystatechange = displayFile;

and

request.send("");

The rest makes sense. I just wasn't sure of the proper syntax for using XMLHttpRequest and I didn't know about readyState and onreadystatechange

  • 0

Pretty much. The readyState is a 0-4 integer value which generalises the state of the object:

0 - uninitialised, 1 - loading, 2 - loading, 3 - interactive and 4 - complete.

catch (e) {
	  return false;
	}

What we are doing is, with a try...catch block, we can attempt to do something, and if an exception is thrown we can catch it. In this case, if we cant create an instance of XmlHttpRequest (or Microsoft.XMLHTTP), we simply return false. Then in the loadFile method, after we have called getXmlHttpRequest, we can determine if the result was succesful by checking if the value of request is truthy (in Javascript, if an object is undefined, or false, its truthy value is false, otherwise it is true, so thats why this works:

if (request) {

request.onreadystatechange = displayFile;

We are telling the XmlHttpRequest to use the function "displayFile" as an event handler for when the readyState of the object changes.

request.send("");

We are invoking the send method of the object, but some browsers don't like having nothing to send, so its best to send an empty string.

  • 0

The getXmlHttpRequest() function is only a wrapper around the various implementations. It checks which functionality is available and then initializes that. If the browser can't initialize the instance, an error is thrown and has to be caught first, that's what the try..catch block is for. By returning false on error, you only need to wrap your code between "if(request) { ... }" to make sure you got a working XmlHttpRequest instance.

If you haven't noticed yet, functions in JavaScript can be assigned as event handlers for properties of objects like XmlHttpRequest. The "onreadystatechange" property for example can be assigned a JavaScript function which will be called once the readyState property changes. Have a look at the difference between these two lines:

request.onreadystatechange = displayFile;
request.onreadystatechange = displayFile();

The first line will assign the function itself to the property, allowing the object to call it whenever it needs to. Internally the object will execute something like this whenever the readyState changes:

this.onreadystatechange();

The second line however will call the function immediately, get its return value and assign that value to the property. This second line will cause problems for two reasons:

  • The request has not been started on that moment yet (request.send hasn't been called yet) so the request.readyState will still be 0 (UNINITIALIZED) or 1 (LOADING), depending whether open() has been called yet. The if-condition will not be fulfilled and displayFile() won't modify anything.
  • Because displayFile() will return void, you'll probably end up with a type error on the line where your trying to assign it to onreadystatechange.

The send() method accepts one parameter, namely the parameters to pass with the request. If you where to send a POST-query to a PHP-file for example, you would use something like:

request.open("POST", url, true);
request.send("login=1&username=johnsmith&password=secret");

For GET requests however, you should add these immediately after the url, e.g.:

url = "http://www.mysite.com/index.php?page=home&loggedin=1";
request.open("GET", url, true);
request.send("");

I hope that helped you. :) However, when you're planning to use this in a production environment, I recommend picking up a JavaScript library such as Prototype or jQuery.

Hmm, it appears I've been beaten. I'll keep this post here for learning purposes. ;)

  • 0
I hope that helped you. :) However, when you're planning to use this in a production environment, I recommend picking up a JavaScript library such as Prototype or jQuery.

Hmm, it appears I've been beaten. I'll keep this post here for learning purposes. ;)

+1 on the JQuery/Prototype.

Teams have spent time creating these free libraries, might as well take advantage of them.

Nice post :)

  • 0

Not sure why but I couldn't quite get your script working for me. I ended up finding a working example on the w3schools page for XMLHttpRequest, which I modified to suit my needs. Thanks for the help though, it's greatly appreciated and did help me learn a few things I didn't know before.

Here's what I have so far. The actual files just contain the last three twitters the people posted.

http://theearlystrike.com/JStest.html

(Oh, and whatever you do please don't look at the rest of that site! It's a horrible temporary design while I work on a prettier one.)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • The sweet release of death has never looked more appealing.
    • Meh, just another dongle-haven downgrade compared to my Surface Pro 7+. Whenever I decide to upgrade in the next decade or so, it certainly won't be another microslop Surface with this enshitification trend they've been having after the Surface Pro 7+. Hopefully a future generation of the Framework 12 will be a real upgrade...
    • This could exactly be how our Sun ends but it's not as simple by Sayan Sen Image by Drew Rae via Pexels An international team led by Université de Montréal (University of Montreal) PhD student Érika Le Bourdais has found that the ancient white dwarf star LSPM J0207+3331 is still pulling in planetary debris, even though it has been cooling for about three billion years. White dwarfs are dense, Earth-sized stellar remnants left behind when Sun-like stars exhaust their nuclear fuel and shed their outer layers. The star, located 145 light-years away in the constellation Triangulum, is the oldest and coldest white dwarf known to have a surrounding disk of dust. The star was first spotted in 2019 by a citizen scientist through the Backyard Worlds: Planet 9 project. Its cool temperature immediately suggested that it was very old, since white dwarfs gradually lose heat over time. Using the W. M. Keck telescopes in Hawaii, astronomers later confirmed that the star shows infrared signals consistent with dust rings formed by asteroids breaking apart under its strong gravity. Such infrared excesses occur when a star emits more infrared light than expected, often because warm dust surrounding it absorbs and re-radiates energy. “This discovery challenges our understanding of planetary system evolution,” said Le Bourdais. “The fact that we still see planetary debris being accreted three billion years after the star became a white dwarf suggests that asteroids, comets, and even planets can remain in orbit around these stars for a very long time.” Spectroscopic analysis—a technique that studies light to identify the chemical elements present in an object—revealed thirteen heavy elements in the star’s atmosphere: sodium, magnesium, aluminium, silicon, calcium, titanium, chromium, manganese, iron, cobalt, nickel, copper, and strontium. Normally, heavy elements sink quickly in hydrogen-rich white dwarfs, making them hard to detect. “We expected to see only a few elements, but we found dozens!” explained Le Bourdais. The research paper adds more detail. The absence of carbon features suggests the debris came from a carbon-volatile-depleted source. The abundance pattern shows slight deficits of magnesium and silicon compared to iron but otherwise resembles Earth-like material. This points to a differentiated rocky body—one whose materials have separated into distinct layers such as a metallic core and rocky mantle—with a metallic core fraction higher than Earth’s. In other words, the star is accreting the remains of a large rocky object, similar in structure to Earth or the asteroid Vesta. “White dwarfs offer one of the only ways we can directly measure the composition of exoplanets,” said Patrick Dufour, co-author and professor at Université de Montréal. “When planetary debris come too close, they are torn apart by the star’s gravity and end up polluting its atmosphere, leaving a detailed chemical fingerprint of its composition.” The team also detected weak Ca II H & K line core emission, making this only the second known isolated polluted white dwarf to show this feature. These are specific spectral signatures produced by ionised calcium and can indicate unusual physical activity in a star’s upper atmosphere. The finding suggests that extra physical processes may be happening in or above the star’s upper atmosphere. The study stresses the importance of including heavy elements in model atmosphere calculations, since leaving them out can distort the inferred structure and lead to inaccurate stellar parameters. Earlier work suggested the star’s infrared excess came from two dust rings. The new analysis shows that a single silicate dust disk—a ring composed largely of rock-forming minerals rich in silicon and oxygen—can explain the observed signal at 11.6 μm, simplifying the picture of the system’s structure. The question of how debris ended up falling into the star so late remains open. One idea is that giant planets in the system slowly destabilised smaller bodies over billions of years. Another possibility is that a passing star disturbed the orbits of debris. “Future observations with the James Webb Space Telescope or archival data found in the European Space Agency’s Gaia mission could help distinguish between a planetary rearrangement and the gravitational effect of a close stellar encounter,” said John Debes, co-author and researcher at the Space Telescope Science Institute. Dufour noted that hydrogen-rich white dwarfs are the most common type, and the coolest among them are the oldest stars in the galaxy. “We didn't have the habit of looking for signs of accretion in them. This unique case motivates us to expand our search to more of these stars.” The findings show that even after billions of years, planetary systems can remain active and complex. Substantial accretion events—the gradual accumulation of surrounding material onto a celestial object—can still occur long after a star’s death, offering a rare window into the composition and fate of distant worlds. Source: University of Montreal, IOPScience This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • Doesn't DDG mainly use Bing?
  • Recent Achievements

    • One Year In
      MadMung0 earned a badge
      One Year In
    • Week One Done
      jefred earned a badge
      Week One Done
    • Apprentice
      JoeyNeo went up a rank
      Apprentice
    • Week One Done
      oliviaexpo earned a badge
      Week One Done
    • Week One Done
      eurospharma62 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      475
    2. 2
      PsYcHoKiLLa
      228
    3. 3
      Skyfrog
      65
    4. 4
      FloatingFatMan
      56
    5. 5
      monterxz
      55
  • Tell a friend

    Love Neowin? Tell a friend!