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

Posted by:

|

On:

|

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

The Express server will cycle through the colors ‘red’, ‘yellow’, ‘green’, and ‘blue’ when the route /colorword is accessed by AJAX. The colorword.html file displays a heading (<h1>) that initially has the color red. On page load, an AJAX request is sent to /colorword to retrieve the color, and the heading’s text and its color is updated accordingly. Clicking the “Change Color” button triggers the AJAX request as well, updating the heading with the new color response.

<!-- colorword.html -->

<!DOCTYPE html>
<html>
<head>
  <title>Colorword</title>
  <script src="/js/jquery-3.7.1.min.js"></script>
  <style>
    h1 {
      color: red; /* Set initial color to red */
    }
  </style>
</head>
<body>
  <h1 id="colorHeading"> </h1>
  <button id="changeColorButton">Change Color</button>

<script>
  $(document).ready(() => {
    const colorHeading = $('#colorHeading');
    const changeColorButton = $('#changeColorButton');
  
    function changeColor() {
      $.ajax({
        url: '/colorword',
        method: 'GET',
        success: (responseText) => {
          colorHeading.text(responseText);
          colorHeading.css('color', responseText); 
        },
        error: () => {
          colorHeading.text('Unable to retrieve colorword');
        }
      });
    }
  
    // Load color on page load
    changeColor();
  
    // Change color on button click
    changeColorButton.on('click', () => {
      changeColor();
    });
  });
</script>
</body>
</html>

Here’s a breakdown of the code:

  • The HTML file starts with the usual document structure, including the <html><head>, and <body> tags.
  • The <title> tag sets the title of the webpage to “Colorword”.
  • The JavaScript library jQuery is included by adding a <script> tag with the source pointing to the library at /js.
  • Inside the <style> tag, there is a CSS rule for the <h1> element, which currently doesn’t have any styles applied.
  • Within the <body> tag, there is an empty <h1> element with the id attribute set to “colorHeading”. This is where the word will be displayed.
  • There is also a <button> element with the id attribute set to “changeColorButton”. This button triggers the AJAX request to change the color.
  • The JavaScript code is enclosed within <script> tags.
  • Inside the JavaScript code, there is a $(document).ready() function, which ensures that the code inside it is executed when the document (webpage) has finished loading.
  • The code defines a changeColor() function that sends an AJAX request to the server to retrieve the color word.
  • The AJAX request is made to the route /colorword using $.ajax(). The success callback function receives the response from the server, and the word is displayed by setting the text of the <h1> element using colorHeading.text(responseText).
  • Additionally, the color of the word is set dynamically by applying the CSS color property to the <h1> element using colorHeading.css('color', responseText).
  • If the AJAX request encounters an error, an error message is displayed in the <h1> element using colorHeading.text('Unable to retrieve colorword').
  • When the page loads, the changeColor() function is called to initially fetch and display the color word.
  • The changeColor() function is also bound to the click event of the “Change Color” button, so clicking the button triggers the AJAX request to change the color.

Content of the server2.js

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

let colorIndex = 0;
const colors = ['red', 'yellow', 'green', 'blue'];

app.get('/colorword', (req, res) => {
  const color = colors[colorIndex % colors.length];
  colorIndex++;
  res.send(color);
});

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

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

The appropriate file structure should resemble the following:

- public
  - colorword.html
  - js
    - jquery-3.7.1.min.js
- server2.js

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

node server2.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/colorword.html

Every time press F5 to refresh or click the change color button, the word and its color will change as shown below.

Posted by

in