Is it possible to incorporate additional variables into my chart.js on the page and access those variables?

In my callback function, I am using the getData(data); method to retrieve JSON data and creating a dataset = [ ]; to extract specific properties from the JSON data.

function call_some_api(getData){
    request('https://someUrl..........',{json:true},(err,res,data) => {
        if (err) {
            console.log(err);
        }     
        if (res.statusCode === 200){
        
             var dataset = [];

             data.forEach((value, key)=>{
                dataset.push(value.close);
            });                
           
            getData(data);     
        }
    });
};

I want to include the dataset variable from my callback function in res.render so that the page can access this variable.

app.get('/chart',function(req,res){
    call_some_api(function(getAPI_data){
       
        res.render('chart',{
            dataChart: getAPI_data,
            
        });
    });
});

I just need my /chart page (handlebars template) to have access to the variable from the callback function in order to build a chart. This is my /chart (handlebars template)

<canvas id="myChart" width="400" height="400"></canvas>
<br><br>

<script>

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
 
           // I just want add in this line below.
            data: dataset,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                stacked: true
            }
        }
    }
});

</script>

This error https://i.sstatic.net/CI1bQ.png

Answer №1

Are you suggesting the addition of a second argument similar to getAPI_data ?

function execute_api_call(getData){
    request('https://someUrl..........',{json:true},(err,res,data) => {
        if (err) {
            console.log(err);
        }     
        if (res.statusCode === 200){
        
             var dataset = [];

             // By the way, this could be achieved more efficiently using `.map` ;)
             data.forEach((value, key)=>{
             dataset.push(value.close);

            });                

           getData(data, dataset);   
  
        }
    });
};

And in your render/http endpoint

app.get('/chart',function(req,res){
    execute_api_call(function(getAPI_data, dataset){
       
        res.render('chart',{
            dataChart: getAPI_data,
            dataset
        });

    });
});

PLEASE NOTE: Code has not been tested, edited within the text.

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

the power of using keywords and prototypes

Greetings! I am currently delving into the realm of JavaScript, hailing from a C++ background. The transition has proven to be quite perplexing for me. Below is a snippet of code that I have been troubleshooting: var someArray = []; nameCompare = function ...

Is there a way to position my character at the exact center of my mouse click coordinates instead of the top left corner?

In my game, players can click on a 2D HTML5 canvas to set a point for their character to move to. However, I've noticed that when I click, the character appears in the lower right corner of where my mouse is clicked. After some research, I realized th ...

Node Js is a lightweight server that allows for easy querying of URLs

I've been exploring various examples but I'm still struggling to understand how it all functions. My goal is quite simple, or so I thought. I was hoping someone could assist me? The task at hand is to establish a server for clients to connect t ...

Reinvent the AJAX functionality

Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...

Executing a Python function using Javascript

I've been attempting to invoke a basic Python method using JavaScript, but unfortunately, I've hit a roadblock. Below is the Python code snippet I'm working with: def main(): return "Hello from Python" And here is the JavaScript code s ...

Managing a two-dimensional array in AngularJS: tips and tricks

I have a JSON source that provides me with a double array: // Function and module code omitted .. $scope.texts = [ ['Small sheep and ham.'], ['Ducks go moo.', 'Helicopters and racecars go bang!'] ]; My goal is to display ...

How can FastApi's 422 Unprocessable Entity error during authentication be resolved?

Even after removing everything inside the function and just printing something, I still get this error. However, when I use fastapi docs and try signing in with that, it works fine. @auth_router.post('/signin') async def sign_in(username: str = F ...

Tips on minimizing object array and extracting its worth using javascript

I am currently facing a challenge with reducing an object array. The array is as follows: arr=[{title: 'AP', CurrentDate: 2019-07-31, Status: 'done', NoOfEvents:'6' }] My goal is to reduce this array object specifically to ex ...

Efficiency issues arising from delayed initialization of local storage in Next.js

I'm facing an issue when trying to reference window; the error message is showing as: ReferenceError: window is not defined I am attempting to initialize a local storage value using lazy initialization: const [colors, setColors] = useState(()=>{ ...

Hold off on loading the slick slider until we receive a response from the API call

My slick slider was working fine, but I encountered an issue where the slider would apply before receiving a response from an API request. This is my first function: fetchProducts () { this.getProducts ().then(response => { ...

Dealing with Typescript: Reducing an object containing other objects

Having some difficulties implementing a reduce function with TypeScript - struggling with types and return value. Facing issues with omitting controls from Storybook, causing two TypeScript errors indicated in the code marked ** ERROR ** Seeking advice on ...

Ways to stop VSC from automatically inserting semicolons

Our development team utilizes a repository that houses a .vscode/settings.json file containing the essential settings for our local workspace. In our work with Vue, we have integrated the Vue extension along with the ESLint extension for JavaScript. The co ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...

Warning: Unidentified JavaScript alert(notification) encountered without declaring a

Imagine this scenario - when I type the following command: open google.com I need JavaScript to detect "open google.com" and prompt me with an alert. The challenge is figuring out how to generate an alert for just "google.com" without including "open". ...

Is there a way to retrieve the Telerik HtmlAttributes values through javascript?

How can I retrieve HtmlAttributes values from a Telerik DropDownList? While I am familiar with using jQuery for this task, I would like to know the correct method for querying these values. @(Html.Telerik().DropDownListFor(model => model.BookingOff ...

Limit the jQuery dialogue button to just one click

My goal is to create a jQuery dialogue box that sends data when the 'OK' button is clicked. The challenge I'm facing is making sure it only sends the data once, regardless of how many times the button is clicked. $.dialogue({ ...

Transfer documents using ajax and javascript

Is there a way for me to directly upload a zip file or png file using my upload button and receive all the data in my upload.php file? I've tried implementing this code, but it doesn't seem to be functioning properly and there are no errors showi ...

Creating PDF files for iPhone using Phonegap

While Phonegap does not have this feature in its API, iOS offers the capability through Quartz 2D. You can find more information about it here. How can I achieve similar functionality in Phonegap for iPhone? As a beginner, any guidance on setting up the n ...

Issue with Sails.js external module functionality within a service

Utilizing restler (https://github.com/danwrong/restler) for making API calls from an external origin. In Sailsjs, helper functions are known as services; I decided to separate my restler code for various HTTP methods like get and post into their own servic ...

Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles: div { position: absolute; height: 50px; width: 50px; background: #900; top: 100px; left: 200px; will-change: transform; transform: translateZ(0); } Afte ...