Troubles encountered when trying to display a Plotly OHLC plot using EJS and transferring data

I'm encountering an issue while trying to display a Plotly OHLC plot in my chart.ejs file with the variable result. Even after using EJS templating and <script> tags for logic, the plot fails to render. To address this, I created a separate file named chart.js to manage the plot's logic but am unsure of how to resolve it.

What might be causing this hurdle, and what steps can I take to effectively showcase the Plotly OHLC plot along with the result data in my EJS template?

index.js:

import express from "express";
import axios from "axios";

const app = express();
const port = 3000;

app.use(express.static("public"));
app.set("view engine", "ejs"); // Setting EJS as the view engine

const base_url = "https://api.coingecko.com/api/v3";

app.get("/", (req, res) => {
  res.render("index.ejs", { result: null, error: null });
});

app.get("/ohlc", async (req, res) => {
  const { id, currency, days } = req.query;

  if (!id || !currency || !days) {
    return res
      .status(400)
      .json({ error: "Please provide id, currency, and days parameters." });
  }

  try {
    const ohlc_result = await axios.get(`${base_url}/coins/${id}/ohlc`, {
      params: {
        vs_currency: currency,
        days: days,
      },
    });

    let day = [];
    let open = [];
    let high = [];
    let low = [];
    let close = [];

    for (let i = 0; i < ohlc_result.data.length; i++) {
      const unix_timestamp = ohlc_result.data[i][0];
      const date = new Date(unix_timestamp);
      const formattedDate = date.toISOString().split('T')[0];

      if (!day.includes(formattedDate)) {
        day.push(formattedDate);
        open.push(ohlc_result.data[i][1]);
        high.push(ohlc_result.data[i][2]);
        low.push(ohlc_result.data[i][3]);
        close.push(ohlc_result.data[i][4]);
      }
    }

    // Defining the OHLC trace
    const result = {
      x: day,
      open: open,
      high: high,
      low: low,
      close: close,
      type: "ohlc",
      increasing: { line: { color: "#17BECF" } },
      decreasing: { line: { color: "#7F7F7F" } },
    };

    console.log("OHLC Result:", ohlc_result.data);
    console.log("Formatted Result:", result);
    res.render("chart.ejs", { result: result });

  } catch (error) {
    console.log(error.message);
    res.status(500).send(error.message);
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
I've comprehended that there is a problem with transmitting result to chart.ejs, but I'm uncertain about its resolution.

Answer №1

The issue at hand revolves around the utilization of variables within the render engine.

When you pass variables to the render() function, they are only accessible during rendering and solely within EJS tags <% ... %>. For more information on EJS variables, refer to this answer.

This implies that in the <script> section, the result variable is not defined. Two potential solutions come to mind:

  1. Transferring EJS Variable to Script

    A potentially quicker and simpler resolution would involve passing the variable directly to the script tag. This can be achieved as follows:

    <script>
        let resultInScript = <%= result %>
        ...
    

    However, there are some considerations. Primarily, many IDEs may flag this as an error, despite its functionality. This occurs because the IDE does not recognize EJS syntax within a <script> and can be rectified by enclosing the tags with string delimiters (", ', `) like so:

    <script>
        let resultInScript = "<%= result %>"
        ...
    

    Another concern relates to objects. Considering the previous issue, regardless of the specific content of the variable in the EJS tags, it will always translate to a string in JavaScript. Therefore, if we simply pass result as before, resultInScript would appear as [object Object] as a string. Combining all elements results in the following format:

    <script>
        let resultInScript = JSON.parse("<%= JSON.stringify(result) %>");
        ...
    
  2. Utilizing AJAX Request to Server

    Alternatively, upon page load, you could initiate an asynchronous request to the server to retrieve the data. To do so, establish a route on your server, such as app.get('/ohcl/data'..., and promptly submit a request to the server after loading the page. Depending on the data's significance, you can execute a GET request with the data as query parameters or employ a POST request with the data encapsulated in the body. While not foolproof security-wise, this method prevents exposing the data as query parameters.

    Implementing this approach enhances page loading efficiency and enables the data/charts to load relatively swiftly, ranging from a few milliseconds to a few seconds based on the data retrieval speed.

I trust this explanation clarifies any uncertainties. Feel free to inquire if further clarification is required.

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

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

Having trouble toggling the navbar on and off in mobile. Error message: Unable to read parentnode of undefined

When I try to make my mobile navbar full screen on a mobile device, the hamburger button works as expected when clicked. Initially, all the links are displayed in full page view, but once I click on a link, it disappears and takes me to the respective sect ...

"Attempting to send JSON data via JsonResult is unsuccessful when trying to send a JSON object directly or using JSON

In my project, I have a class that looks like this: I've created a JsonResult method in the controller which takes an object of this class as a parameter: [HttpPost] public JsonResult NewAreaCode(AreaCode model) { return Json ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Retrieve the value of a variable by using either an HTTP GET or POST request

Here's the HTML code snippet that I'm working with: <head> <h1>Sample Page</h1> </head> <body> <form method="POST" action=""> Enter Keyword <input type="text" name="key"> ...

The peculiar formatting issue with the jQuery datepicker that arises when adding more months

When adjusting the numberOfMonths parameter to a higher value such as 6, I noticed that the datepicker display appears unusual with the background extending further than expected. Take a look at my demonstration on jsfiddle: http://jsfiddle.net/zw3z2vjh/ ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

When making an asynchronous call, only the initial character is shown in the (HTML) listbox elements

I have a query regarding AngularJS compatibility with IE9. My issue is with a modal window containing a patient list. <div class="modal-header"> <h3 class="modal-title">Patient list</h3> </div> <div class="m ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

Creating a 3D object using three.js framework

When playing video games, I often notice a common pattern where hovering the mouse over an object triggers a gradient highlight around its 2D representation. To recreate this effect in my Three.js scene, I started by setting up the necessary raycaster vari ...

What is the method for updating the form action to alter the hash without causing a page reload?

My website is designed to show dynamic data based on the information following the '#' in the URL. Surprisingly, when I manually change this value in the URL, the page doesn't reload. However, if I modify it within a form on the site, the we ...

I am having trouble with using document.getElementById().value to retrieve text input. Can anyone help me understand why it's not

It's puzzling to me why document.getelementbyid().value isn't working as expected. Upon inspecting the console, no input seems to be sent or printed out in the console. function callApi() { var keyword = document.getElementById('user_ ...

Troubles with retrieving API search results using Vue computed properties

I've recently developed an Anime Search App using Vue.js and the new script setup. I'm currently struggling to access the search results in order to display the number of titles found. The app is fetching data from an external API, but it's ...

"Using Jquery to Extract Content from CKEditor: A Step-by-Step Guide

I have integrated the CKEditor control in my asp.net project, here is an example: <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server"> Can anyone recommend a method to retrieve the content from this editor using jquery? ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Close the parent electron window while keeping the child window open

I am currently working on a project where I need to create an electron app that displays a splash screen initially and then opens a new window before closing the splash screen. However, despite my efforts, I am facing challenges in achieving this functio ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

What is the best way to determine the position of an internal SVG element in relation to the viewport of an outer SVG element?

Consider an SVG element with various components: <div style="margin-left:50px; width: 100%; min-height: 400px;"> <svg> <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%"> <svg x="20" y ="50" style ...