Attempting to populate HTML content retrieved from my MySQL database

Currently, I am attempting to retrieve HTML content stored in my MySQL database using nodejs.

The products are being retrieved from the database successfully.

export async function getAllProducts() {
    try {
        const response = await fetch('http://localhost:4000/productos');
        
        if (!response.ok) {
            throw new Error(`Error: ${response.status} - ${response.statusText}`);
        }

        const json = await response.json();
        return json;
    } catch (error) {
        console.error('Error fetching products:', error.message);
        throw error;
    }
}

However, when trying to insert it into the HTML, I encounter this error:

import { getAllProducts } from "../products.js"

//instances
const burger_container = document.getElementById("burger-container");
const smash_container = document.getElementById("smash-container");
const salad_container = document.getElementById("salad-container");
const drink_container = document.getElementById("drink-container");

const fillProducts = async () => {
    const products = await getAllProducts();

    products.forEach(product => {
        const category = product.category;

        let container;

        // Directly comparing with strings
        if (category === "hamburguesa") {
            container = burger_container;
        } else if (category === "smash") {
            container = smash_container;
        } else if (category === "ensalada") {
            container = salad_container;
        } else if (category === "bebida") {
            container = drink_container;
        }

        // Creating element within the category 
        if (container) {
            container.innerHTML += `<div>${product.name}</div>`;
        }
    });
}

Please assist me with this issue :)

I am endeavoring to fetch the products from the database and display them in the HTML using container.innerHTML.

Answer №1

give this a shot.

const fetchData = async () => {
    // Implement your logic here
}
module.exports = fetchData;

const fetchData = require("./data.js");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

How to redirect to a different view or controller using ASP.NET and AngularJS

How can I open the View located at /Home/CreateItem after clicking on the Add button? What do I need to include in my code? $scope.Add = function() { console.log('working'); } This is how Index.cshtml looks like: <script src="~/ ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...

React setState issue experienced only on initial click due to API lag

My goal is to develop a web app using the Poke API to display multiple Pokemon. I have added buttons to allow users to "change the page" and switch the API URL to view the next or previous set of Pokemon. However, I'm facing an issue where the buttons ...

Refreshing EJS Variables through an AJAX call

Currently developing a bespoke Shopify order management application using Node.js, Express, and EJS as the template engine. The goal is to dynamically display updated JSON data from the Shopify API without the need to refresh the page, such as new orders a ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Verify if the contract address corresponds to a token and retrieve the token details, such as its symbol

Can I use web3 to retrieve token information such as symbol and total supply similar to the etherscan API pro endpoint tokeninformation by providing the contract address? I'm interested in determining whether the addresses I collect are tokens or reg ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

Tips on automatically adjusting the width of a div to fit the content, maintaining center alignment, and ensuring the contents float to the left

I am facing an issue with a div element that has multiple children. My goal is to have the children neatly fit to the bottom left of the grid when the window expands, utilizing the next available space efficiently. However, as the div expands with the wind ...

Go back to the previous operation

Utilizing ajax to verify if a username is available by checking the MySQL database. If the username is already taken, it will return false to the form submit function. index.php $("#register-form").submit(function(){ var un = $("#un").val(); $.aj ...

The data from the server is inaccessible to node.js

I am a beginner in nodejs and jquery, trying to retrieve data from a server and use it to update a webpage: Using jquery on the client side: I would like to change the text inside '#info' element with the data fetched from the server. $('# ...

Increment Counter on Presence of Items in a Table with jQuery

Does anyone know how to properly increment a counter in jQuery based on certain words found within a table? I am currently encountering an issue where my counter is only increasing by 1 instead of the expected 2. Here is the HTML and jQuery code snippet: ...

What is the best way to handle query string parameters when routing in Next.js?

One of the challenges I am facing is related to a URL structure like this: bar?id=foo When I navigate to this URL using router.push('bar?id=foo'), everything works perfectly. However, if I directly access the route in the browser, the query st ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...