Search code examples
javascripthtmlnode.jshandlebars.js

How to append html formatted data from node js server to html file in client side?


I'm trying to build a site in plain javascript, node and handlebars that, trough a quote calculator, the user could request a list of several items to the owner of the site. The data formatted in json such as:

{ "item": "candy", "brand":"delicious candy" }

would be inserted by the user in index.html. The site then would perform some validations and then send it to the server through the fetch api attached to a event in a button somehow like 'send quote'

app.post('/api', (request, response) => {
let quote = request.body;
response.render('admin', quote);

Then HandleBars would insert the data in html such as:

<h1> Candy </h1>
<h2> Delicious candy </h2>

And here is where I'm stuck, I'm capable to visualize in the console the response of the api call, and apparently is sending back to the browser the data I want, but I cannot wrap my mind in how could I append this HTML to a HTML file called admin.html.

enter image description here

aproximation of data flow


Solution

  • Are you at all familiar with jQuery? What you could do is create an empty paragraph tag in your Handlebars HTML.

    <p id="candyData">
    
    </p>
    

    Then, in your JS file where you're adding your event listener for the submit button on your form, query the paragraph by ID.

    const candyData = document.querySelector('#candyData');
    

    Now, in your fetch to your server, it could look something like this to get the value to the page.

    fetch('/url').then((response) => {
      response.json().then((data) => {
        if (data.error) {
          candyData.textContent = data.error;
        } else {
          candyData.textContent = data.candyDataObj // candyDataObj should be accessed based on how you're storing the data.
        }
      });
    });
    

    Don't forget to also load in the script tag in your HTML file.

    <script src="/scripts/app.js"></script> <!-- the src path should be updated per your directory -->