'Displaying function values onto an already existing EJS template

I need to display a value from a JS file (indexRoutes.js) into an input box on an EJS template (calculator.ejs), I have included the script via a footer I have made.

This is the code for the JS Function I have:

router.post("/calculator", (req, res) => {
  let ethAddress = req.body.ethereumAddress;
/*BEGINNING OF CALCULATION METHOD
  /* PART 1 For getting data, using node-fetch .json to convert the data into an array of objects*/
  function APIRetrieval() {
    var userTransactions = [];
    var totalValue = 0;
    fetch(
      `https://api.etherscan.io/api?module=account&action=txlist&address=${ethAddress}&startblock=0&endblock=99999999&sort=asc&apikey=${APIKey}`
    )
      .then((data) => {
        return data.json();
      })
      .then((retrievedData) => {
        // Extract just the results from the Javascript object for a Javascript object of just the transactions.
        userTransactions = retrievedData.result;

        // This loop takes all values from all previous transactions and adds them together for a number to be used in the calculation of emissions.
        for (var i = 0; i < userTransactions.length; i++) {
          // console.log(userTransactions[i].gasPrice);
          let currentValue = Number(userTransactions[i].gasPrice);
          totalValue = totalValue + currentValue;
        }
      });
  }
  APIRetrieval();
});

This is the code for the EJS Form that I have:

<form action="/calculator" method="POST">
  <div class="form-group px-5 mt-4">
    <div class="d-flex justify-content-center">
      <label for="ethAddress">Ethereum Address</label>
    </div>
    <div class="d-flex justify-content-center mt-2">
      <input
        type="string"
        id="ethereumAddress"
        name="ethereumAddress"
        class="form-control"
        placeholder="Enter Ethereum Address"
      />
    </div>
  </div>
  <div class="d-flex justify-content-center">
    <button type="submit" class="btn btn-primary mt-4">Calculate</button>
  </div>
  <div class="d-flex justify-content-center mt-4">
    <label for="emissionValue">Total Emission Price To Offset</label>
  </div>
  <div class="d-flex justify-content-center mt-2 mb-4">
    <input
      type="string"
      id="emissionValue"
      name="emissionValue"
      class="form-control"
      placeholder=""
      value=""
      readonly
    />
  </div>
</form>

I want to display the totalValue value from the JS file, inside the emissionValue input after the post request has been submitted, the post request is fully functioning and does work, I just do not know how to replace the empty value inside emissionValue whilst using NodeJS and Express.

I understand it does not come with a DOM, however, I have no idea how to tackle this. I have also tried to look into JSDom but I cannot understand this exact scenario.

This is my File Structure: File Structure



Solution 1:[1]

Supposing your ejs file is named calculator.ejs and that you added already in your main file the ejs middleware and ejs setup.

In your endpoint, when you send the response, you can send it like this:

router.post("/calculator", (req, res) => {
  let ethAddress = req.body.ethereumAddress;
/*BEGINNING OF CALCULATION METHOD
  /* PART 1 For getting data, using node-fetch .json to convert the data into an array of objects*/
  function APIRetrieval() {
    var userTransactions = [];
    var totalValue = 0;
    fetch(
      `https://api.etherscan.io/api?module=account&action=txlist&address=${ethAddress}&startblock=0&endblock=99999999&sort=asc&apikey=${APIKey}`
    )
      .then((data) => {
        return data.json();
      })
      .then((retrievedData) => {
        // Extract just the results from the Javascript object for a Javascript object of just the transactions.
        userTransactions = retrievedData.result;

        // This loop takes all values from all previous transactions and adds them together for a number to be used in the calculation of emissions.
        for (var i = 0; i < userTransactions.length; i++) {
          // console.log(userTransactions[i].gasPrice);
          let currentValue = Number(userTransactions[i].gasPrice);
          totalValue = totalValue + currentValue;
        }
      });
      return totalValue;
  }
  const totalValue = APIRetrieval();
  res.render("calculator.ejs", {totalValue: totalValue});
});

You bassically render that file and send values to it, values that you can use inside it
In your calculator.ejs you can use now:

<div class="d-flex justify-content-center mt-2 mb-4">
          <input
            type="string"
            id="emissionValue"
            name="emissionValue"
            class="form-control"
            placeholder=""
            value="<%= totalValue =>"
            readonly
          />
        </div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1