Alwaysblue
Alwaysblue

Reputation: 11840

Update an element automatically in a website using NodeJs

I am still in early stages of my programming and I was thinking about creating something which does API calls after every x seconds and update my website with new content.

My intial goal is to populate a table with the content obtained from API using FOR loop (.ejs page).

Now, I want to update just those rows and columns (created from FOR loop) of my webpage after x seconds instead of refreshing my entire page. How can I achieve this (Updating those rows and columns) ?

Consider stock market website, where it just updates the stock price, instead of entire page.

Thanks for your help in advance

Upvotes: 0

Views: 3299

Answers (2)

Dan Prince
Dan Prince

Reputation: 29989

The most popular way to solve this problem is to store the data you obtain from the other API in your database, then create an endpoint that serves the most recent version of that data as JSON.

Then at the client side, you make periodic requests to the server to fetch the content and updates a part of the page to show the newest data available.

This could be as simple as:

// server side (if you use express)

app.get("/data", (req, res) => {
  database.getMostRecentEntry()
    .then(data => res.json(data))
    .catch(err => res.status(500).end());
});


// client side

function fetchMostRecentData() {
  fetch("/data")
    .then(response => response.json())
    .then(data => updateView(data))
    .catch(err => showError(err));
}

function updateView(data) {
  let container = document.getElementById("app");

  container.innerHTML = `
    <tr>
      <td>${data.name}</td>
      <td>${data.value}</td>
    </tr>
  `;
}

function showError(err) {
  console.error(err);
  alert("Something went wrong");
}

// call fetchMostRecentData once every 10s
setInterval(fetchMostRecentData, 10000);

Now, this isn't a very robust solution and there are some fairly serious security problems, but it's a starting point.

From here, you should look into using a frontend framework (rather than updating innerHTML yourself). You could also look at using websockets, rather than serving the data through a HTTP endpoint.

Upvotes: 2

Nicholas Siegmundt
Nicholas Siegmundt

Reputation: 869

I'd look into using expressjs in combination with node.js to build your website. Then using ajax inside your html to accomplish the rest api call updates.

Upvotes: 1

Related Questions