The issue of outdated data persisting in Chart.Js even after an AJAX request has

Currently, I am utilizing VueJS 2.0, Laravel 5.3, and Chart.JS.

The page is constructed by initiating AJAX requests with vue.js to retrieve data from Laravel in the form of a JSON object. Some pages require multiple AJAX calls for different sets of data. On one particular page, the chart displays correctly initially. However, upon changing the date, while the page updates accordingly, chart.js retains the data from the previous date, visible when hovering the mouse over the former area.

To provide a clearer understanding, I have provided a gif video link here: . The video demonstrates that data from the selected date (2017-01-08) is displayed correctly, but when moving the mouse towards the center, it shows the old data from the default date (2017-01-09).

The AJAX request function made to Laravel(PHP) is as follows:

        fetchEvents: function (date = null) {

            this.loading = true;

            this.$http.get('data/daily/' + this.selectedDate).then(function (response) {
                this.data = response.body;
                this.selectedDate = this.data.date;
                this.drawChart();
                this.loading = false;
            }, function (error) {
                console.log(error);
            });
        },

This function subsequently calls darwChart():

        drawChart: function () {

            // Code for Pie charts mostly remains the same as below

            // Comparison with previous dates
            var ctx3 = document.getElementById("previousDaysPolar");

            var data = [this.data.nxt_summary.total_count,
                        this.data.total_previous_week.data, 
                        this.data.total_previous_month.data, 
                        this.data.total_previous_year.data];

            var previousDays = new Chart(ctx3, {
                type: 'polarArea',
                data: {
                    labels: ['Selected Date: ' + this.data.date, 
                            'Previous Week: ' + this.data.total_previous_week.date, 
                            'Previous Month: ' + this.data.total_previous_month.date, 
                            'Previous Year: ' + this.data.total_previous_year.date],
                    datasets: [{
                            label: 'Order types',
                            data: data,
                            backgroundColor: [
                                'rgba(96, 110, 103, 0.2)',
                                'rgba(202, 207, 0, 0.2)',
                                'rgba(191, 180, 143, 0.2)',
                                'rgba(242, 239, 233, 0.2)'
                            ],
                            borderColor: [
                                'rgba(96, 110, 103, 1)',
                                'rgba(202, 207, 0, 1)',
                                'rgba(191, 180, 143, 1)',
                                'rgba(242, 239, 233, 1)'
                            ],
                            borderWidth: 1
                        }]
                },
                options: {
                    responsive: true
                }
            });

        }

Upon viewing the video, it appears that this function performs as expected by updating the data passed onto the chart. Can you provide any insights as to why the old data persists alongside the new data?

Answer №1

Clearing the chart before updating it with new data is essential for ensuring that the new chart accurately reflects the updated information. This practice is recommended in the chart.js documentation:

.clear()

This method clears the chart canvas and is commonly used between animation frames. It can be particularly useful for maintaining accuracy when updating charts.

// Clear the canvas where myLineChart is displayed myLineChart.clear(); // => returns 'this' for chainability

For more details on prototype methods, refer to the documentation.

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

Looking for a way to implement a delay in JavaScript code?

Greetings! I'm currently working on an XMHHttp request, but the website's load time is causing me to only reach ReadyState = 3 and Status = 200. In order to proceed, I need a solution that will wait until ReadyState = 4, but with the added requir ...

<head> Javascript codes are failing to run

Currently utilizing JQuery Mobile, my goal is to navigate between pages with minimal script loading each time a page loads. Essentially, I want to import all the general scripts (such as JQuery.js, jquery_mobile.js, main.js, etc.) ONCE for all pages. In m ...

Information fails to show up upon navigating to a different page

Having trouble with a survey form that utilizes ajax to call data. When the user clicks cancel, I want it to navigate to another page displaying a list of data using ajax in listview format. While the navigation part is successful, the issue lies in not di ...

Ways to identify the location of the mouse pointer within a specific div

My dilemma involves a rectangle span measuring 100 pixels in width and I am seeking for the user to choose between 0-100%. Upon clicking anywhere within the div horizontally, the corresponding value should be saved and promptly displayed to the user throu ...

JavaScript and React.js encounter glitch in AWS Cognito authentication function

I'm currently troubleshooting a issue in my code where there is no validation to prevent a user from signing up with the same email twice: Below is my onSubmit code: async function handleSubmit(event) { event.preventDefault(); setIsLoading( ...

Having a problem with Angular 6 services using providedIn: 'root' resulting in an empty object in the component

I have a service located in src/core/services/api.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor() { } test() { console.log('hello from ...

Utilizing React JS and Express to efficiently filter AJAX responses

I am currently developing a MERN (Mongo, Express, React, Node) application. My approach involves using Ajax to extract data from the MongoDB. My next goal is to refine the response by implementing a query in the GET request. Unfortunately, I seem to have ...

Incorporate Object names and Variable names in Javascript programming

I have an object named res and a variable named lea. I need to concatenate. For example: let lea = "abc"; let res = { abc:'steve' }; console.log(res.lea); So my output should be steve. I tried it like this: console.log(res.`${lea}`); ...

NodeJS: Warning of unhandled promise rejection when attempting to change password

During my work on implementing password changing functionality in NodeJS, I encountered the following error while processing a request: (node:16220) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent. at validateHeader ...

Transfer documents via AJAX and PHP

I am having an issue with my PHP script that involves a dataTable and a browse button to add new videos to the Database and display them in the DataTable. Although the entry is successfully added to the database, the file itself is not being copied from i ...

The function getObjectById is not functioning properly and is throwing an error: TypeError - scene.getObjectById is

Just starting out as a new programmer in the world of Javascript and three.js, I encountered an error where getObjectById is not working properly. The specific TypeError message reads: "scene.getObjectById is not a function." My goal was to access an obje ...

Tips for illustrating the connection between two distinct schemas during a discussion

I am facing an issue where I need to consider two different Schemas that can be used in place of the user property within the Conversation model. How should I approach representing this? It could either be a Student who has messaged or a User who sends a m ...

Executing JavaScript code from a web browser in Node.js

I have created a simple JavaScript code in AngularJS and I would like to be able to execute it in both Node.js and the browser depending on the situation. While I am aware of the tools like browserify or lobrow that allow running Node.js code in the brows ...

TempData function malfunctioning when used in conjunction with AJAX requests

Within my ASP.NET MVC 6 project, I encounter a situation where multiple AJAX calls are made in parallel from a standard MVC controller to consume endpoints that return views. These AJAX calls interact with separate endpoints within the same controller - ea ...

Can node.js be run on a server alongside another JavaScript file?

I have developed a small web application on my personal server. It consists of a few HTML, CSS, and JavaScript files. I am looking to incorporate Node.js with the following simple code: var mysql = require('mysql'); var fs = require('fs&apos ...

Unable to transmit information using Postman for registration API

I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, ye ...

What is the best way to prevent a command from being displayed in the terminal when using node-pty and xterm?

Currently, I am leveraging xterm.js, node-pty, and electron to create a node repl-like terminal similar to repl.it. In order to execute a file and display the output in the terminal, I am using the following code snippet: ptyProcess.write("vm.runInNewCont ...

Looking to run a JavaScript command without the need for any triggering events?

Is there a way to execute the following JavaScript code without using any event and have it run at the start, onLoad of the page? function calculateDiscount() { var totalPrice = document.getElementsByClassName("Total")[0].innerHTML; var discountedPr ...

TypeAhead.js and Bloodhound displaying an uneven quantity of search outcomes

I have a frontend setup with TypeAhead and Bloodhound integration, fetching JSON data from a Play/Scala server. The version of Typeahead being used is 0.11.1. Here is how the implementation looks: HTML: <div id="typeahead" class="col-md-8"> < ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...