Dynamic content loading on web pages with Ajax & Express (3)

Posted by:

|

On:

|

It is the third example using JQuery AJAX function and Express JS.

Create a static HTML page called “log.html” and place it in the “public” folder of the project. Inside log.html, there are JavaScript code that executes when the “log.html” page is loaded. This code should use AJAX to send a request to the server’s “/log” route every 10 seconds. Once the AJAX response is received, extract the real timestamps from the response and populate the “log.html” page with an unordered list (ul) containing these timestamps.

<!-- log.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Log Page</title>
  <script src="js/jquery-3.7.1.min.js"></script>
</head>
<body>
  <h1>Log Page</h1>
  <ul id="timestamps"></ul>

  <script>
    $(document).ready(function() {
      var timestampsList = $('#timestamps');

      // Function to populate the timestamps on the page
      function populateTimestamps(timestamps) {
        // Clear previous entries
        timestampsList.empty();

        // Add new timestamps as list items
        timestamps.forEach(function(timestamp) {
          timestampsList.append('<li>' + timestamp + '</li>');
        });
      }

      // Function to send AJAX request to /log/add
      function addTimestamp() {
        $.ajax({
          url: '/log/add',
          method: 'GET',
          data: {
            timestamps: timestampsList.find('li').map(function() {
              return $(this).text();
            }).get().join(',')
          },
          success: function(response) {
            populateTimestamps(response);
          },
          error: function() {
            console.log('Error occurred while adding a new timestamp.');
          }
        });
      }

      // Get the initial timestamp when the page is loaded
      $.ajax({
        url: '/log',
        method: 'GET',
        success: function(response) {
          populateTimestamps(response);
        },
        error: function() {
          console.log('Error occurred while retrieving initial timestamps.');
        }
      });

      // Add a new timestamp every 10 seconds
      setInterval(addTimestamp, 10000);
    });
  </script>
</body>
</html>

Here’s a breakdown of the code:

  1. The HTML file begins with typical HTML tags, including the <!DOCTYPE html> declaration, the opening <html> tag, and the <head> section.
  2. Inside the <head> section, there is a <title> tag that sets the title of the page to “Log Page.” Additionally, there is a <script> tag that includes the jQuery library (version 3.7.1) from a local file named “jquery-3.7.1.min.js.” Make sure the file path is correct and the jQuery library is accessible from that location.
  3. Moving to the <body> section, there is an <h1> tag that displays the heading “Log Page.”
  4. Below the heading, there is an empty <ul> (unordered list) element with the id “timestamps.” This element will be populated dynamically with real timestamps obtained from the server.
  5. Inside the <script> tag, the JavaScript code is wrapped within the $(document).ready() function. This ensures that the code executes when the DOM (Document Object Model) has finished loading.
  6. The JavaScript code defines a function named populateTimestamps(timestamps) which takes an array of timestamps as input. This function clears any previous entries in the <ul> element with the id “timestamps” and then appends new <li> (list item) elements to the <ul> element, each containing a timestamp from the input array.
  7. Another function defined in the JavaScript code is addTimestamp(). This function sends an AJAX (Asynchronous JavaScript and XML) request to the server’s “/log/add” route using the jQuery $.ajax() method. The request is a GET request, and it includes the current timestamps present in the <ul> element as a query parameter named “timestamps.” The success callback function is responsible for populating the page with the updated list of timestamps received in the response.
  8. The JavaScript code also includes an AJAX request to the server’s “/log” route when the page is initially loaded. This request retrieves the initial timestamps from the server and populates the page using the populateTimestamps() function.
  9. Lastly, the setInterval() function is used to call the addTimestamp() function every 10 seconds. This triggers the AJAX request to the “/log/add” route periodically to add new timestamps received from the server to the page.

Content of the server3.js

const express = require('express');
const app = express();
const port = 3000;

// Route for retrieving initial timestamps
app.get('/log', function(req, res) {
  // Simulated initial response with real timestamps
  var timestamps = [
    new Date().toString()
  ];

  res.json(timestamps);
});

// Route for adding a new timestamp
app.get('/log/add', function(req, res) {
  // Simulated response with a new real-time timestamp
  var newTimestamp = new Date().toString();

  // Retrieve the existing timestamps from the query parameter
  var existingTimestamps = req.query.timestamps || '';

  // Add the new timestamp to the existing ones
  var updatedTimestamps = existingTimestamps.split(',');
  updatedTimestamps.push(newTimestamp);

  res.json(updatedTimestamps);
});

app.use(express.static('public'));

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

I want to explain the route /log/add:

  1. When a GET request is made to “/log/add”, the route handler function is executed.
  2. Inside the route handler, a new timestamp is generated using new Date().toString(). This creates a string representation of the current date and time.
  3. The existing timestamps are retrieved from the query parameter timestamps using req.query.timestamps. If the query parameter is not present or empty, existingTimestamps is set to an empty string.
  4. The existing timestamps are split into an array using split(','). The split is performed based on the comma (‘,’) delimiter, which separates the timestamps in the query parameter.
  5. The new timestamp is added to the updatedTimestamps array using push(newTimestamp).
  6. The res.json(updatedTimestamps) statement sends the updated timestamps as a JSON response back to the client. The array of updated timestamps is converted to JSON format and sent in the response body.

The appropriate file structure should resemble the following:

- public
  - log.html
  - js
    - jquery-3.7.1.min.js
- server3.js

Run the Express application by executing the following command in the Ubuntu terminal:

node server3.js

Make sure both Orange Pi and PC have the same subnet and connect to the same router or network switch. On the PC’s web browser, enter the following URL where 192.168.21.26 is the IP address of the Orange Pi.

http://192.168.21.26:3000/log.html

When log,html is loaded, a real time stamp is shown. Then a new read time stamp is added to the list every 10 seconds.

Posted by

in