Problem

You have designed a web application with frontend and backend. The frontend page wishes to send an Asynchronous And JavaScript XML (AJAX) request to the backend and update a small portion of the page with the response that is text. The AJAX was introduced to make our websites look more like Desktop applications in a way that we only update a portion/ part of the page instead of refreshing the whole page and get it all updated. The request is taking place in the background of the web browser

solution

We will use the classic way for sending an HTTP request in the background. All it needs from the browser is to have JavaScript enabled. The code will be executed when we click a button and we will update the contents of the page dynamically without refreshing the whole web page.

We will have a text file named “info.txt” that will be retrieved by the request. The text file will have some raw data for now just for testing. For example:

this is a test text file
test line number 2
end

In JavaScript we have available out of the box the XMLHttpRequest object. This object along with some other ones are given by the web browser to make our lives easier. We will use this object to perform HTTP requests. Let’s create a function for loading the info file and call it loadText(). It will be as follows:

function loadText() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("demo").innerHTML = this.responseText;
  }
  xhttp.open("GET", "info.txt");
  xhttp.send();
}

The function creates the object xhttp, then it sets an anonymous function to be called on its onload event. Afterwards it opens a new HTTP GET request for the info.txt. Note that it is pointing at the localhost. And finally it’s sending it. When the request is resolved and the response is returned, the onload function will be executed and it will locate the #demo on the DOM and set its innerHTML to the responseText which is gonna be the contents of the info.txt.

Let’s create the HTML page and plug this function in a script tag and glue it with the button click.

<!DOCTYPE html>
  <html>
    <body>

      <div id="demo">
        <h2>Simple AJAX example</h2>
        <button type="button" onclick="loadText()">Load Text</button>
      </div>

      <script>
      function loadText() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
          document.getElementById("demo").innerHTML = this.responseText;
        }
        xhttp.open("GET", "info.txt");
        xhttp.send();
      }
      </script>

    </body>
</html>

Save the above as .html file e.g. ajax_example.html

Running

In order to run the code above, it requires that is served by a web server. The simple HTTP server packaged in Python will do the trick in this case but there are more tools available. Recall, for starting the web server, we change to the directory where the above HTML file is located. Also, the info.txt should be in the same directory.

Start the web server:

python3 -m http.server

Go to localhost:8000 as that’s the default port number and see the HTML page. It should show the directory and its contents:

Now, click at the .html file. The browser should show the following:

Then click the “Load Text” button and check it’s working.

It works! The info.txt is loaded on the div with id demo. The only problem is that the new lines are not shown correctly. It printed it as one line but it was saved as 3 lines in the text file. That is because is not using HTML break tags (<br/>) but simple new line feeds (\n) in ASCII format. We could have fixed that by adding some JavaScript logic and manipulate the responseText but let’s change the info file.

Updating the text file to the following will correct the new line issue:

this is a test text file<br/>
test line number 2<br/>
end
Output

Now, when the button is clicked it should show the text file as follows:

conclusion

In this post we saw a very simple example of sending an AJAX request to retrieve some text data and update the webpage on a particular part instead of the whole page. See more tutorials on JavaScript.


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x