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

Posted by:

|

On:

|

Dynamic content loading involves updating or loading content on a web page without the need for a complete page refresh. JavaScript plays a crucial role in enabling dynamic content loading by facilitating the retrieval and manipulation of data asynchronously. This approach offers several benefits:

  1. Enhanced User Experience: Dynamic content loading provides faster and smoother interactions with the website, resulting in improved user engagement and satisfaction.
  2. Reduced Server Load: Instead of reloading the entire page, only specific data is requested, which reduces the server load and minimizes bandwidth usage.
  3. Real-time Data Display: Dynamic content loading enables the display of real-time data, such as live chat updates or notifications, providing users with up-to-date information.

AJAX (Asynchronous JavaScript And XML) is a well-established method for achieving dynamic content loading. It enables the retrieval of data from the server without the need for a complete page reload. While the name suggests XML usage, AJAX is commonly employed with JSON for efficient data exchange.

Workshop : using AJAX

Step 1

Create a directory “public” under the Express.js project directory. Inside the public folder, create a html file (lastvisit.html) containing a paragraph <p> with an id “timestampParagraph” and include an external JavaScript file named “script_lastvisit.js” to handle the last visit timestamp functionality.

Content of “lastvisit.html”

<!DOCTYPE html>
<html>
<head>
  <title>Time for Last Visit</title>
</head>
<body>
  <h1>Time for Last Visit</h1>
  <p id="timestampParagraph"></p>
  <script src="script_lastvisit.js"></script>
</body>
</html>

Step 2

Create a javascript file called “script_lastvisit.js” within the directory “public” with the following codes

document.addEventListener('DOMContentLoaded', () => {
  const timestampParagraph = document.getElementById('timestampParagraph');
  
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        const responseText = xhr.responseText;
        timestampParagraph.textContent = `This page was last viewed ${responseText}`;
      } else {
        timestampParagraph.textContent = 'Unable to retrieve timestamp';
      }
    }
  };
  
  xhr.open('GET', '/lastvisit', true);
  xhr.send();
});

What does “script_lastvisit.js” do?

It sets up an event listener for the “DOMContentLoaded” event, which triggers when the HTML document has finished loading. Within the event listener, it retrieves an HTML element with the ID “timestampParagraph” and assigns it to the variable “timestampParagraph”.

The code then creates an XMLHttpRequest object, which facilitates communication with the server. It defines an anonymous function as the onreadystatechange event handler for the XMLHttpRequest object. This function is executed whenever the readyState property of the XMLHttpRequest changes.

Inside the onreadystatechange function, there is a conditional statement that checks if the XMLHttpRequest is done (readyState === XMLHttpRequest.DONE). If it is, another conditional statement checks if the status is 200 (indicating a successful response). In that case, it retrieves the responseText from the XMLHttpRequest object, and updates the text content of the “timestampParagraph” element to display the last viewed timestamp.

If the status is not 200, indicating an unsuccessful response, it updates the text content of the “timestampParagraph” element to display an error message.

Finally, the code opens a GET request to to the server with route “/lastvisit” and sends the request asynchronously using the XMLHttpRequest object.

In summary, this code retrieves the content of the “/lastvisit” file from the server and updates a specific HTML element with the retrieved timestamp or an error message, depending on the response from the server.

The key aspect of AJAX is the asynchronous nature of the request, where the page does not need to be fully reloaded to fetch and update specific data. Instead, it dynamically retrieves data from the server in the background and updates the content without disrupting the user experience.

Step 3

To create an Express route in a file named server1.js within the project directory that handles HTTP GET requests for the route /lastvisit and send back the lastVisitTimestamp. When the response is received by AJAX, it will modify the paragraph in lastvisit.html to update the text ” This page was last viewed [timestamp]” where [timestamp] contains the timestamp of the last page view.

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

let lastVisitTimestamp = '';

app.get('/lastvisit', (req, res) => {
  res.send(lastVisitTimestamp);
  lastVisitTimestamp = new Date().toISOString();
});

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

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

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

node server1.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/lastvisit.html

Every time press F5 to refresh, the last visit date time will be updated.

Alternative coding method

Instead of using the XMLHttpRequest object, one can achieve the same result by using jQuery’s AJAX function. Additionally, the JavaScript code can be embedded directly within the lastvisit.html file.

Here’s an updated version of the lastvisit.html file that includes the jQuery library <script src=”/js/jquery-3.7.1.min.js”></script> and the JavaScript code:

<!DOCTYPE html>
<html>
<head>
  <title>Time for Last Visit</title>
  <script src="/js/jquery-3.7.1.min.js"></script>
</head>
<body>
  <h1>Time for Last Visit</h1>
  <p id="timestampParagraph"></p>
  
  <script>
  $(document).ready(() => {
    const timestampParagraph = $('#timestampParagraph');
  
    $.ajax({
      url: '/lastvisit',
      method: 'GET',
      success: (responseText) => {
        timestampParagraph.text(`This page was last viewed ${responseText}`);
      },
      error: () => {
        timestampParagraph.text('Unable to retrieve timestamp');
      }
    });
  });
  </script>
</body>
</html>

Using AJAX from jQuery offers the advantage of a more structured and concise code. I recommend downloading the jQuery library file and hosting it locally. The lastvisit.html file should be placed in the public directory, which can be specified as the static file directory using express.static('public'). The appropriate file structure should resemble the following:

- public
  - lastvisit.html
  - js
    - jquery-3.7.1.min.js
- server.js

Following this file structure ensures that the lastvisit.html file resides within the public directory and that the jQuery library file (jquery-3.7.1.min.js) is located inside the js subdirectory of the public folder. This arrangement facilitates the correct functioning of the code.

To download jQuery library file, I type https://code.jquery.com/jquery-3.7.1.min.js in the browser. The browser may display the content of the file, but I can still download it by right-clicking anywhere on the page and selecting “Save As” or “Save Page As” (the exact wording may vary depending on your browser). Choose a location on the computer to save the file, making sure to keep the .js file extension intact. After downloading the jQuery library file, host it on the local server by placing it in the appropriate directory, such as the js subdirectory within the public folder.

Posted by

in