Executing Client-Side Function Upon Data Retrieval in a Node.js Application

Within my node.js Express application, there exists a route like this:

router.get('/devices/:id/visualize', catchErrors(deviceController.visualizeDevice));

This route points to the following controller:

exports.visualizeDevice = async (req, res) => {
  const device = await Device
    .findOne( { _id: req.params.id } )
    .populate({
      path: 'states',
      options: { limit: 999, sort: { changed: 'asc' }}
    });
  confirmOwner(device, req.user);
  res.render('visualizeDevice', { title: `Visualize Device: ${device.name}`, device });
};

The associated view looks like this:

extends layout

block content
  -
    let statuses = device.states;
  //- pre= h.dump(statuses)
  .calendarContainer
    .calendar 
      .calendarHeader
        .yearHeader
        ul.calendarHeaderDays
          li Sat
          li Sun
          li Mon
          li Tue
          li Wed
          li Thu
          li Fri
        .arrow.top#upArrow △
        .days

When I check the dumped statuses, they align with what is expected:

[
  {
    "changeType": "unlocked",
    "_id": "5c635f3dff415e0980ebbd1e",
    "author": "5b74a5b26513f70a28f8776a",
    "device": "5c635eb3ff415e0980ebbd19",
    "changed": "2019-02-10T18:00:00.000Z"
  },
  {
    "changeType": "unlocked",
    "_id": "5c6366f3194a4800155cfac1",
    "author": "5b74a5b26513f70a28f8776a",
    "device": "5c635eb3ff415e0980ebbd19",
    "changed": "2019-02-13T00:38:11.935Z",
    "__v": 0
  },
...
]

My intention is to have the following client-side script executed:

function populateCalendarDays(startDate=new Date()) {
  //  repeat 5 times for 5 weeks on the calender
  for (let j = 1; j <= 5; j++) {
    //  select the first day of the week
    let dayEl = document.querySelector(`.week${j}Day1`);
    //  repeat for 7 days
    for (let i = 0; i <= 6; i++) {
      if (getStatus(day) === "locked") {
        let lockEl = document.createElement('I');
        lockEl.classList.add('locked');
        dayEl.insertAdjacentElement('afterBegin', lockEl);
      }
      //  move to the next element
      dayEl = dayEl.nextElementSibling;
    }
    //  move to the next week
    startDate = addWeeks(startDate, 1);

  }
}

function getStatus(day) {
  status = "unlocked";
  for (let i = 0; i < statuses.length; i++) {
    if (compareAsc(day, parseISO(statuses[i].changed)) === 1) {
      status = statuses[i].changeType;
    }
  }
  return status;
}

However, upon running it, I encounter an error stating

Uncaught ReferenceError: statuses is not defined
. How can I adjust this code to allow the front-end function to access and interact with the backend data properly?

Answer №1

One way to send data to the front end is by including it in a script tag within the template.


script var statusData = !{JSON.stringify(statuses).replace(/<\//g, '<\\/')}

Learn how to pass variables from Jade template to script file here.

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 best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Confused about the concept of an SWR subscription

As I navigate through SWR's various features, there is one that has caught my attention: SWR-subscription. The concept of "subscribing to real-time data sources with SWR" is unfamiliar to me and I am seeking an explanation along with a straightforward ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

Error: The Stripe webhook payload must be submitted as either a string or a Buffer

I'm currently working on setting up a subscription system using Stripe. I have mostly followed the code from their documentation, but I keep encountering the following error: Webhook signature verification failed. Webhook payload must be provided as a ...

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Determine if an element is being hovered over using jQuery

How do I determine if the cursor is hovering over an element using jQuery or JS? I attempted to use $('#id').is(':hover'), but it doesn't seem to be functioning as expected. It's worth mentioning that I am calling this line ...

After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

What is the implication of not utilizing body parser or express.json() in my application?

As a beginner in the world of backend development, I have recently learned that both bodyparser and express.json() are used to parse the incoming request (body from the client) into the request object. However, what would be the outcome if I choose not to ...

When a <a href> link is clicked, the Struts action should open as a popup

I have a form on my jsp page, <form action="test1_action" name="test" method="post" id="test"> Additionally, I have two distinct links: link1 and link2. When link1 is clicked, the form should be submitted with the action test1_action. $('#l ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Unable to write or upload error in a Node Express application

My GET and POST APIs are functioning properly, however, my app.put is not working as expected. Upon sending a PUT request to localhost:3001/contacts/1 using Postman, I am unable to see the console.log output: app.put('/api/contacts:id', (req, ...

The Dynamic Kendo Grid construction encountered an invalid template issue

In my project, I'm working on creating a dynamic Kendo UI grid with columns that are dynamically generated. However, I'm encountering an issue where the data is not rendering properly onto the grid. The backend of this project involves using ASP ...

Exploring ExpressJS: Distinguishing between app.local and res.local - which one should you use?

I'm in the process of learning how to use Express, and within my application I have implemented middleware that transfers the session object from the Request to the Response. This allows me to access it in my views: app.use((req, res, next) -> r ...