Utilizing Chart.js to visualize live data from a dynamic MySQL dataset

Struggling to create a dynamic dataset for my Chart.js project, specifically with the data obtained from getpromorevenuechart.php. Here's an example of the dataset:

[{"mmyy":"2019-12","promocode":"promo1","amount":"2776"},{"mmyy":"2020-01","promocode":"promo1","amount":"1245"},{"mmyy":"2020-01","promocode":"promo2","amount":"179"}
]

This is my current code snippet:

    function getPromoRChartData() {
    var city = document.getElementById("cityselect").value;
$.ajax({
        type: 'GET',
        url: 'getpromorevenuechart.php',
        dataType: 'json',
        data: {  city:city, },
        success: function(response) {
          // Code here

        }
});
. . .

Desiring the graph to display data in this format:

data: {
        labels: ["2019-12", "2020-01"],
        datasets: [{
            label: 'promo 1',
            data: [2776, 1245]
        },
        {
            label: 'promo 2',
            data: [0, 179]
        }
        ]
    },

Need assistance on iterating through and formatting the data properly for the chart. Any guidance would be appreciated.

Edit:

. . .

If I remove the [{}] around dyndatasets I get the error:

TypeError: Attempted to assign to readonly property.

and if I remove the brackets from dynlabels, this happens:

https://i.sstatic.net/ei2JQ.png

Oddly enough... copying directly from the console and pasting works fine, so could it be a formatting issue?

Answer №1

Below is a snippet of code that demonstrates how you can transform the response data into the required format (labels and datasets) for chart.js.

const response = [ 
   { 
      "mmyy":"2019-12",
      "promocode":"promo1",
      "amount":"2776"
   },
   { 
      "mmyy":"2020-01",
      "promocode":"promo1",
      "amount":"1245"
   },
   { 
      "mmyy":"2020-01",
      "promocode":"promo2",
      "amount":"179"
   }
];

const labels = Array.from(new Set(response.map(c => c.mmyy))).sort();
const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort();
const datasets = promocodes.map(pc => ({ label: pc, data: []}));
labels.forEach(l => {    
    for (let pc of promocodes) {
    let city = response.find(c => c.mmyy == l && c.promocode == pc);
        datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0);
    }
});

console.log("labels: " + JSON.stringify(labels));
console.log("datasets: " + JSON.stringify(datasets, undefined, "  "));

For further reference, visit this JSFiddle

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

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Sharing a Twitter thread using Twit library with Node.js

I have been using Node.js along with the npm Twit module to post tweets on Twitter, and while it works for a single tweet, I am facing issues when trying to post multiple tweets as a thread. When attempting to post a series of tweets together, they do not ...

Steps for incorporating "about minutes ago, about hours ago, etc;" into a .filter for an Angular/Ionic v1 project

Can someone help me figure out how to incorporate phrases like "from now," "ago," etc. into a JS filter in my ionic v1 project for WordPress without using UTC Date? I am currently working on an Ionic v1 app that is native to WordPress, so it's crucia ...

implement a user input field within a div using JavaScript

I have created a lightbox in my HTML page with the following structure: <div id="container"> <input type="text" id="user_1" name="user_1" value="user_1"/><br> <input type="text" id="user_2" name="user_2" value="user_2"/>< ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

How can I retrieve the elements that have been removed using $pull in mongoose?

Currently, I am utilizing $pull to eliminate a subdocument from an array within a document. It may be pertinent to note that the subdocuments in my case contain _id and are therefore indexed. Here is the JSON schema description: user: { _id: Strin ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

Adjusting Flexslider to perfectly accommodate the height and width of the window dimensions

Currently, I am using Flexslider version 1.8 and seeking to set up a fullscreen image slider on my homepage. My goal is to adjust the slider to match the browser window size. While experimenting with width:100% and height:auto properties, I have managed t ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

Utilize the $(#id).html(content) method to populate the following column with desired content

Here is a snippet of my HTML code: <div class="row margin-top-3"> <div class="col-sm-7"> <h2>NFTs</h2> <div class="table-responsive"> <table class="table table-bordered&qu ...

I'm having trouble locating the corresponding end tag for "<%". How can I resolve this issue?

Here lies the issue: <% for(let i = 0; i < <%= elements %>.length; i++){ %> <li><%= elements[i] %></li> <%}%> ...

unable to retrieve the value of the table row with a particular class designation

I'm currently working with a table code and I need to retrieve the value of the table row with the class "highlight". However, when trying to do so with the code below, I'm getting a null result. Can someone please assist me? Table name: itemtab ...

What is the best way to establish a limit on the number of characters that can be entered into an input field in a React form?

Currently, I am creating a tool to check the strength of passwords based on their length. However, I am unsure of how to precisely determine if a password falls within specific length ranges such as "between 5 and 10 characters" or "between 20 and 30 cha ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

Unallocated functions found within Web Sockets Objects

I am currently utilizing javascript (p5.js) in combination with node.js using express and socket.io. Within my code, I believe the issue lies within this specific section: for (var i = 0; i < 3; i ++){ for (var j = 0; j < 3; j ++){ ...

Steps for applying background color to a chosen element

Using a specific template, I have listed topics in the following way: //Template used for topic list display %li.topic{:topic_slug => "<%=topic.slug%>", :topic_name =>"<%=topic.text%>"} %a{href: "#!/topics/<%=topic.slug%>" } <%= ...

Send the 'key' parameter to the React component

Attempting to pass a parameter named "key" to a react component is resulting in it not functioning properly. However, when I use "keyy" instead of "key," it works as intended. It appears that using "key" as a parameter name may be causing issues due to it ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...