HTTP Basics

noun_20804_cc.png

HTTP is how computers talk to each other. It stands for Hyper Text Transfer Protocol, and is an agreed upon method that defines how computers transfer information between one another. Whenever you use a browser (like chrome or firefox) to view a website you are using the HTTP protocol.

This post will show you how to make the contents of one file (a simple.txt file) display inside a completely different file without having to reload the page.

 1. First create a file named “name.txt”

Fill it with Lorem Ipsum and save it in a folder.

 2. Set up an HTML file.

The easiest way to do this is to go to example.com and copy the source code. In the body, remove the contents of the paragraph tag and give it an id of ‘response’. Then save the file in the same folder as the name.txt file

<p id="response"></p>

 3. Create a new HTTP object

Create a <script></script> tag at the bottom of the html file, just inside the </body> tag. The HTTP request will be made within <script></script> tags. A HTTP request is started by creating a new HTTP Object using XMLHttpRequest().

var request = new XMLHttpRequest(); // creates a new HTTP object called 'request'

 4. Add the open method to the object you just created.

request.open("GET", 'name.txt',false); // submits a GET request to the file 'name.txt'

The open() method is used to configure a HTTP request. The .open(method, url, async) method takes three parameters.

a. ‘Method’ refers to the type of request e.g. ‘GET’ or ‘POST’.
b. The ‘url’ refers to the location of the file on the server that you want to exchange data with.
c. The ‘async’ is set to either ‘true’ or ‘false’. Setting ‘async’ to false means that JavaScript will not continue to execute the rest of the scripts until the server response is ready. If the server is slow the application might stop.

 5. Then send the request.

request.send(null);

After the HTTP request has been configured, the .send() method is used to actually send the request to the server.

 6. Console log the responseText

Now log the contents of the ‘name.txt’ file into the console by adding the following below the send method:

console.log(request.responseText);

HTTP objects have several properties. One of these properties is .responseText() and turns the data stored in the file you are requesting into a string.

 7. Open the HTML file in your browser

Now open your HTML file in firefox (it won’t work in chrome) and open up the console. The contents of the name.txt file should now be printed to the console as a string.

You have just successfully loaded the contents of one file into another file without refreshing the page. And you did it with the HTML Request.

 8. Refresh the file

If you want the content to actually show up in the HTML page, as opposed to the replace the console log with:

document.getElementById('response').innerHTML = request.responseText;

 Doing the whole thing Asynchronously

So far we have been synchronously calling the .open method on the HTTP request object (by setting the ‘async’ parameter to ‘false’). This means that while the method is executing, no other functions on the page can work.

Setting the ‘async’ parameter to ‘true’ means that JavaScript doesn’t have to wait for the server response and can execute other scripts on the page. The open method then effectively runs in the background.

 9. Set the ‘async’ parameter to ‘true’.

request.open("GET", 'name.txt',true);
// asynchronously calling the 'open' method
request.send();

However this also means you have to wait until you know the response is ready before accessing the ‘responseText’ property of the HTTP Object.

To do this, we need to modify a property of the HTTP Object called ‘onreadystatechange’. This property needs to be set to a function that executes every time the state of the request changes.

Inside the function we check another property called ‘readyState’. This can take the values from 0 to 4.

0 mean request not initialized.

1 means the server connection has been established.

2 means the request was received.

3 means the request is being processed.

4 means the request is finished and the response is ready.

The state that you will need to be checking for is 4. When the response is ready, the response text can be displayed on the page.

 10. Modify the .onreadystatechange property

Replace the document.getElementById('response').innerHTML = request.responseText; with:

request.onreadystatechange = function() {
    if(request.readyState == 4) {
        console.log(request);
        document.getElementById('response').innerHTML = request.responseText;
        // this last line grabs the element on the page with the id #response and changes its text to the text from the file that was opened.
    };
};

Open your HTML file up in firefox again (it still won’t work in chrome). The contents of the name.txt file should now be printed inside the <p> tag.

 References

  1. http://eloquentjavascript.net/1st_edition/chapter14.html
  2. http://www.w3schools.com/dom/dom_httprequest.asp
 
1
Kudos
 
1
Kudos

Now read this

Today I Learnt Some HTML.

Total Days 2 Total Earned $0. I learnt that a “tag” is a bit of code that tell a browser what to do. For a tag to work you have to <open> it and then </close> it. If you want some text on a webpage you put it inside a... Continue →