Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side:

const leaderboard = [[dog,cat],[car,bus],[foo,bar]]

const toJson = JSON.stringify(leaderboard)
        res.render('games/dodge.ejs', {
                leaderboard: toJson
 })    

This is how the ejs file receives it:

<div data-leaderboard="<%= leaderboard%>"></div>

Next, there is the client-side JavaScript file dodge_leaderboards.js

const leaderboardData = document.querySelector("[data-leaderboard]")

console.log(leaderboardData)

Upon running this code, I encounter an error that states Uncaught SyntaxError: Identifier 'leaderboardData' has already been declared (at dodge_leaderboards.js:1:1). Additionally, the console.log returns null.

I am attempting to assign the arrays within the larger array to individual variables, but now I am facing issues with a simple console.log. What do you think might be causing this problem? I am also curious to learn how to parse the array.

Answer №1

Success! I finally fixed it by remembering to add ".dataset.leaderboard" after the variable leaderboardData

const leaderboardData = document.querySelector("[data-leaderboard]")

console.log(leaderboardData.dataset.leaderboard)

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

What is the correct location for the webpack.config.js file within a React project?

I recently inherited a React project that I need to continue working on, but I have never used React before. I've been advised to use a web worker in the project and have found a tool that seems suitable for my needs: Worker Loader The suggested meth ...

Encountered an issue loading the file or assembly netwonsoft.json following recent updates to Visual Studio and NuGet

Recently, I updated Visual Studio to update 4 before updating all packages through NuGet. However, upon attempting to run my website, I encountered the following error: An exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll ...

Getting information from a PHP script using jQuery AJAX with the (webpack based) ZURB Foundation Framework

Currently, I am working on a ZURB Template project that was set up using the foundation client. As part of my work, I have already completed some initial tasks such as enabling ES7 features async/await in Babel7 (ZURB Foundation utilizes gulp as taskrunner ...

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

Leverage the power of JSON objects within your Angular.js application

Is it possible to request a JSON object, such as the one in employes.json file: {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} Then, how can I util ...

Accessed a property that is not defined on the instance during rendering

One of the components I'm working on displays data that is defined in the component's state. To access this data, I created a getter: export default createStore({ state: { foo: true, }, getters: { getFoo: state => state.fo ...

What is the best way to fetch a matched route pattern in Express JS?

My goal is to have my logger middleware record each matched route when the response is sent. However, the issue lies in the fact that there could be any number of nested subroutes within the application. Imagine a scenario where I have the following setup: ...

PHP not receiving POST information from $.ajax call

My JavaScript triggers a POST method when the datepicker loses focus, calling the script rent-fetch-pick-up-point.php. However, the PHP script gets stuck at the if-statement because it's not receiving the POST data. The datepicker is associated with a ...

I possess a collection of server-side questions and answers. How can I display them one by one in an EJS template upon clicking?

Here is the path I have chosen: app.get('/test', (req,res)=>{ res.render('index.ejs',{qData: [{Q1},{Q2},...]}); }) Is there a way to display this qData sequentially on the client side with each click? Imagine I have two buttons la ...

What are the steps to successfully install OpenCV (javascript edition) on Internet Explorer 11?

I'm currently experiencing issues with getting the OpenCV javascript version to function properly on IE11 for contour detection. While my code runs smoothly on all other up-to-date browsers, I am encountering errors such as: TypeError: Object doesn&a ...

Locate Vue Components That Are Persisting

After loading my app and immediately taking a Chrome memory heap snapshot, I found the following results. https://i.stack.imgur.com/QB8u3.png Upon further exploration of my web app and then returning to the initial loaded page to take another memory heap ...

Tips for creating dynamic row styles in a fluid table layout?

Could someone help me figure this out? I'm not familiar with JavaScript and need assistance as I've never created it, only edited existing scripts. I have a layout with two tables side-by-side. On mobile devices, the second table is pushed below ...

In search of a render function that can effectively apply styles to HTML strings using React JS

I have been struggling to convert the result field value, including HTML attributes string, into respective styles for one column in my antd table. Below is the string I am trying to convert: The exhaust air requirements for fume hoods will be based on m ...

Enabling communication between App.js and a separate class in React

How can I integrate React Scheduler with JSON data in my app and pass shifts and functions from App.js to DataSheet.js for updating the data? Is there a more efficient way to enable database updates directly from DataSheet? App.js: import React from &apos ...

What is the best way to duplicate a Typescript class object while making changes to specific properties?

I have a Typescript cat class: class Kitty { constructor( public name: string, public age: number, public color: string ) {} } const mittens = new Kitty('Mittens', 5, 'gray') Now I want to create a clone of the inst ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

Calculating the sum of table columns with the help of knockout.js

Is there a way to calculate the table columns using knockout.js? I am familiar with jQuery but new to knockout.js and unsure how to approach this. Instead of generating the table data using JSON, I would like to directly create it in the HTML table itself. ...

Retrieve the function-level variable within the while loop's else statement

Struggling with node.js, I find myself facing the challenge of accessing a variable declared at the start of a function from an else statement nested within a do while loop: function myFunction(){ var limit = 2000; var count; var total; va ...

The image from the local source displays correctly in the initial component without any issues, but it does not appear in its corresponding detail component

My blog has a component for displaying posts and another component for showing the details of a single post as seen below. A key point to note is that while the blog component can load and display images, the blog details component cannot. Why is this? A ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...