Error: The symbol $ is not recognized in this context. The issue occurred at line 1, character 11 in the HTML file

Apologies in advance for any grammatical errors in my English, it's not my native language. I'm encountering difficulties in adding a product fetched from the API to my cart when clicking the button. Upon clicking, the console displays the following error:

Uncaught ReferenceError: ${product.id} is not defined at HTMLAnchorElement.onclick (VM#### index.html:1:11)

The variable ${product.id} represents the ID of the respective product.

Here is the snippet of code causing the issue:

let products = [];


// GENERATE PRODUCT CARDS
const generateCards = (arrayFiltered) => {
    let generatorCards = ``;
    arrayFiltered.forEach((product) => {
        generatorCards += `    <div class="card-responsive col mb-5">
    <div class="card h-100">
        <!-- Product image-->
        <img class="card-img-top" src="${product.thumbnail}" alt="..." />
        <!-- Product details-->
        <div class="card-body p-4">
            <div class="text-center">
                <!-- Product name-->
                <h5 class="fw-bolder">${product.title}</h5>
                <!-- Product price-->
                $${product.price}
            </div>
        </div>
        <!-- Product actions-->
        <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
            <div class="text-center"><a class="btn btn-outline-dark mt-auto mb-2 btn_add-cart" href="#" onclick="addToCart(${product.id})">Add to Cart</a></div>
        </div>
    </div>
</div>`;
    })
    document.getElementById('container-products').innerHTML = generatorCards;
};


// ADD TO CART FUNCTION
const addToCart = (productId) => {
    const foundIndex = products.findIndex(product => product.id == productId);
        cart.push(products[foundIndex]);
        Toastify({
            text: "Product successfully added to cart! :D",
            duration: 2500,
        }).showToast();
        cartReduce();
};


// FETCH DATA
API_URL = 'https://api.mercadolibre.com'
API_ENDPOINT_SEARCH_NICKNAME = '/sites/MLA/search?nickname='
const fetchDataBase = () => {
    fetch(API_URL + API_ENDPOINT_SEARCH_NICKNAME + 'FVENTAS+ONCE')
        .then((response) => response.json())
        .then((data) => {
            products = products.concat(data.results);
            console.log(data);
            generateCards(products);
        })
}

fetchDataBase();
<section>
        <div class="container px-4 px-lg-5 mt-5">
            <div id="container-products"
                class="row gx-4 gx-lg-5 row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 justify-content-center">
            </div>
        </div>
    </section>

HELP NEEDED URGENTLY FOR MY FINAL JAVASCRIPT PROJECT! Thank you so much in advance!

If you want to check out the live page to better understand my issue, here is the link to the GitHub page:

Answer №1

ChrisG provided the solution in a comment. Appreciate it!

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

Arrange elements in a vertical flow based on the height of the container

I am attempting to alter the direction of Elements to be vertical. Here is an example: By default, HTML elements are displayed horizontally like this:- #container { position: absolute; width: 400px; height: 200px; border: 1px solid gree ...

React Typescript: Error - Attempting to access properties of undefined while attempting to read 'map'

I've been attempting to display user data on a card component fetched from jsonplaceholder using axios. However, I keep encountering an error message: "TypeError: Cannot read properties of undefined (reading 'map')". Despite trying various s ...

What is the best way to securely transfer data from a Node/Express server to the client using JavaScript, ensuring sanitized HTML and preventing cross-site scripting (X

What is the best method to securely pass data from an Express backend to a client-side JavaScript in order to render it in the DOM using client-side rendering, while also allowing sanitized whitelist HTML and preventing XSS attacks? For example, if the No ...

Retrieving various data attributes from checkboxes

I am currently working on creating a quiz that contains questions with multiple answers. Here is the HTML code I have implemented: <div>What combinations will result in 4?</div> <input type="checkbox" id="qid" class="checks" data-correct=" ...

The response from Ajax in JavaScript may come back as undefined

I'm facing an issue with my JavaScript function that uses AJAX to call a PHP function inside a PHP class. The problem is that the console.log shows undefined. function SpinTimeTotal(){ $.ajax({ type:"POST", url: &qu ...

What is the best way to download an updated social media post for a Django user?

Objective A user has the ability to edit their own posts by clicking on the edit button, making edits, and then saving the changes. Issue Editing a social media post does not result in the changes being saved. Overview Create a new post similar to how ...

Tips on incorporating svgo into a vite react project

One of the great features I've found in create-react-app is the ability to use SVGs as React components: import { ReactComponent as NotFound } from '@/assets/images/not-found.svg' function Error() { return ( <div> <NotF ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

Is it possible to use Postman to automatically generate request body based on Runner input file?

I rely on Postman for sending requests to a Kanban API, but the data varies each time. For instance, the request body always includes an ID for the Kanban card to be placed on the board, {{External_Card_ID}}, but it may not always include a plannedFinish ...

Using Angular and Jade to pass an array from a controller to script tags

I am trying to figure out how to access an array in my controller and display it accurately within the <script> tags in my jade template. For instance: Controller.js $scope.myArray = ["item1","item2"]; Within my index.jade: script. var clien ...

Make a button gradually disappear after being clicked using jQuery

Recently delving into the realm of jQuery, I've encountered a stumbling block with this particular code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="add">Add</button> ...

Node.js Mistake - 'Attempting to import outside of a module is not allowed'

I’m currently immersed in a React project, and my focus is... Firebase.js import firebase from 'firebase/app' import 'firebase/database' import 'firebase/auth' const firebaseConfig = { apiKey: process.env.FIREBASE_AP ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

Struggling to generate a TrackballControls instance

Every time I try to create a TrackballControls object, I encounter an error message stating "THREE.TrackballControls is not a constructor". Here's a simple example: <!doctype html> <html> <head> <title>Trackball Contr ...

Clicking to remove added child element

I have written a script that creates an image popup when the site loads. Here is the code: <script type="text/javascript"> function showPopup() { var div = document.createElement('div'); div.className += 'popup'; div.inne ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

What is the best way to send a value to a controller function with Ajax when a button is clicked, and then immediately redirect to a new page?

One of my challenges involves a button labeled Next that triggers a page change: <a class="disabled" href="step"> <button class="btn btn-primary launch-btn disabled next">NEXT</button> </a> Upon clicking this button, I have an ...

Interconnected dropdown selections for multiple dropdown menus

I have successfully implemented a jQuery function that populates the second dropdown options based on the selection of the first dropdown option. However, I am facing an issue with having multiple instances of this functionality in rows. When I change the ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

Navigating through the fiery depths of Angular's $q promise

Is there a way to improve the readability of this Angular Q implementation call? It seems like the d3 loading should be parallel to data loading in this case. d3Q.init() .then(function(d3) { scope.loadHistoryData() .then(function( ...