• 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

    • ESET 19.1.14 by Razvan Serea NOD32 for Windows is the best choice for protection of your personal computer. Almost 20 years of technological development enabled ESET to create state-of-the-art antivirus system able to protect you from all sorts of Internet threats. ESET Internet Security boasts a large array of security features, usability enhancements and scanning technology improvements in defense of your your online life. ESET Internet Security ESET Internet Security keeps your computer or laptop safe with intelligent multi-layered protection combining proven antivirus, antispyware, firewall, anti-rootkit and antispam capabilities. Based on ESET NOD32 Antivirus, it protects you from viruses, worms, spyware, and all Internet threats. It conserves resources and improves computer speed. You are protected at the highest level while you work, social network, play online games or plug in removable media. ESET NOD32 Antivirus Your best defense against viruses, trojans and other forms of malware—and the top choice for IT professionals. Powered by the ThreatSense® engine with advanced heuristics, which blocks far more unknown threats than the competition. The latest generation of the legendary ESET NOD32 Antivirus takes your security to a whole new level. Built for a low footprint, fast scanning, it packs security features and customization options for consistent and personalized security online or off. ESET Smart Security Ultimate protection for everyday web users, thanks to ESET’s trademark best balance of detection, speed and usability. Stay safe from viruses and spyware. Stay protected from ransomware - Blocks malware that tries to lock you out of your own data. Receive free support by email or telephone in your local language, wherever you are. Bank and shop online more safely - automatically secures transactions on internet banking sites, and helps to protect you on online payment gateways. Stop hackers from accessing your PC - Personal Firewall prevents hackers from gaining access to your computer and keeps you invisible when you use public Wi-Fi. Keep your kids safe online - block unwanted internet content by categories or individual websites and keep your kids safe online with Parental Control. Safer webcam and home router - Get an alert when anyone tries to access your webcam, and check your home router for vulnerabilities. Safely store passwords, and encrypt your data. Safely store, generate and prefill your passwords, and encrypt your files and removable media (USB keys). Includes protection for smartphones and tablets. Protect all of your devices - mix and match security protection for up to 3 or 5 devices. ESET Security Ultimate ESET Security Ultimate offers all-in-one protection with antivirus, anti-malware, and anti-phishing features. It includes a personal firewall, secure online banking, and a password manager for enhanced security. Parental controls and data encryption keep family and sensitive information safe. It also provides regular updates to ensure you're always protected against the latest threats. It's user-friendly and ensures comprehensive digital security, perfect for those seeking reliable protection without complexity. ESET 19.1.14.0 changelog: Fixed: GUI crahes Fixed: IPM issues Download: ESET NOD32 Antivirus 64-bit | NOD32 Antivirus 32-bit | ARM 64 | ~ 80.0 MB (Free Trial) Download: ESET Internet Security 64-bit | ESET Internet Security 32-bit Download: Eset Smart Security Premium 64-bit | Eset Smart Security Premium 32-bit Download: ESET Security Ultimate 64-bit | ESET Security Ultimate 32-bit ARM64: Antivirus | Internet Security | Smart Security | ESET Security Ultimate Link: ESET Home Page Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • +1 for Rufus. I bought NTLite a few years ago to scrape all the bloat out of Windows 11. It is not a perfect solution as there is a steep learning curve if you don't really know what you are doing (me included). I have finally got a Windows install that just works. I only keep things I use and nothing else.
    • Personally ive been using searxng, self hosted, although there are public instances out there too (https://searx.space).  Its shocking when I occasionally go into google or bing and see how bad they've become in the last year 
    • You guys claim everyone you don't like is Hitler, so you've already ruined that. Boy who cried wolf and all that.
  • 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
      487
    2. 2
      PsYcHoKiLLa
      226
    3. 3
      Skyfrog
      65
    4. 4
      monterxz
      56
    5. 5
      Nick H.
      55
  • Tell a friend

    Love Neowin? Tell a friend!