Cannot transmit JSON API information to Chart JS

Having trouble fetching and displaying data in a chart? I've been struggling with it for the past few days—any help would be appreciated.

My code fetches and reads data perfectly fine, passing it to an HTML table, but I can't seem to pass it to the chart... feeling confused)

Here's the snippet of my code:

function loadReport() {
    
    var dateFrom = document.getElementById("date1").value.toString();
        var dateTo = document.getElementById("date2").value.toString();
        var apiurl = "<?php echo $user->getFromTable_MyId("integration_api", "users"); ?>";
        var pubID = "<?php echo $user->getFromTable_MyId("id", "users"); ?>";
    
        $.getJSON(apiurl + '&Target=Affiliate_Report&Method=getStats&fields[]=Stat.affiliate_info1&fields[]=Stat.payout&fields[]=Stat.conversions&fields[]=Stat.clicks&filters[Stat.affiliate_info1][conditional]=EQUAL_TO&filters[Stat.affiliate_info1][values]=pop_24&filters[Stat.date][conditional]=BETWEEN&filters[Stat.date][values][]=' + dateFrom + '&filters[Stat.date][values][]=' + dateTo + '&sort[Stat.date]=desc', function(data) {
     //if you want to add more on balance just enter number in value
     
     values9=[0]
     values8=[0]
     values7=[0]
    var data, id, conversion, clicks, payout, statDate = "";
    var id = '';
        var clicks = '';
        var conversion = '';
        var payout = '';
        
    for (i in data.response.data.data) {
        
       const chartDateArr = data.response.data.data[i].Stat.date;
        const chartClicksArr = data.response.data.data[i].Stat.clicks;
        console.log(chartClicksArr);
        const chartConversionsArr = data.response.data.data[i].Stat.conversions;
        const chartPayoutArr = data.response.data.data[i].Stat.payout;


        // Code continues...

For screenshots of the results outputs, follow these links: chart, table, console

JSON text result from API fetch:

{
  // JSON response content...
}

Answer №1

Make sure to move the chart generation code out of the loop that handles the data. This is why the datapoints are displaying as single numbers instead of arrays. Extract the chart code from the loop and provide it with the respective data arrays (you can use `map` for this purpose).

const data = {
  "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "page": 1,
      "current": 50,
      "count": 7,
      "pageCount": 1,
      "data": [{
          "Stat": {
            "affiliate_info1": "pop_24",
            "source": "",
            "affiliate_info5": "",
            "affiliate_info4": "",
            "affiliate_info3": "",
            "affiliate_info2": "",
            "payout": "0.000000",
            "conversions": "0",
            "clicks": "7",
            "date": "2024-03-04"
          }
        },
        ...
      ]
    }
  }
}

const chartDateArr = data.response.data.data.map(item => item.Stat.date);
const chartClicksArr = data.response.data.data.map(item => +item.Stat.clicks);
const chartConversionsArr = data.response.data.data.map(item => item.Stat.conversions);
const chartPayoutArr = data.response.data.data.map(item => item.Stat.payout);

//Chart code START
var ctx3 = $("#line-chart").get(0).getContext("2d");
var myChart3 = new Chart(ctx3, {
  type: "line",
  data: {
    labels: chartDateArr,
    datasets: [{
        label: "Revenue",
        fill: false,
        backgroundColor: "rgba(40, 153, 51, .3)",
        borderColor: "rgba(40, 153, 51, .7)",
        data: chartPayoutArr
      },
      ...
    ]
  },
  options: {
    responsive: true
  }
});

//Chart code END
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>

<div>
  <canvas id="line-chart"></canvas>
</div>

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

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Customizing X-axis labels for server-side chart rendering with PhantomJS and JSON data

Currently, I am utilizing phantomjs to generate png images of a highchart using a json file in a commandline script. Since the data is provided in JSON format, I am unable to apply xAxis.labels.formatter as I would in a web client version. However, since t ...

Unable to trigger JSON success

I am facing an issue with my JSON payload as the success function is not triggering. Any help that can be offered would be greatly appreciated. JLS Although I can see the value in the console, the query seems to be working fine but it is not formatted in ...

Result array, employed as an input for auto-suggest functionality

I’m currently working with an array where I am iterating over an object from an API endpoint that is in stdClass format: foreach($searchResults->hits as $arr){ foreach ($arr as $obj) { $fullType = $obj->_source->categories; print_r($fu ...

Managing fresh data entries in meteorology

In my current setup, I have a "requests" collection and I have successfully set up publications on the server side and subscriptions on the client side. My question is, how can I effectively handle new records in MongoDB? Specifically, I would like to re ...

The 'formGroup' property cannot be bound in the LoginComponent because it is not recognized as a valid property of the 'form'

When working on my Angular project and using ReactiveFormsModule to create a form, I encountered an error message during the build process. The specific error was: src/app/security/login/login.component.html:11:13 - error NG8002: Can't bind to ' ...

Which is more advantageous in this scenario: using .fail() or .timeout()?

When it comes to handling timeouts on my $.ajax() calls for a jQueryMobile project, I have discovered two potential methods. The .fail() function appears to be the more generic option: if the call fails for any reason, an error stack is returned and then ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

What is the process for searching a sentence and making replacements under certain conditions?

When it comes to the address: _# _, and for the specified phrase: _# some specific words _. I am looking to identify a phrase. if (phrase includes address) then delete the address. const stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind ...

Manipulating knockout.js observables within a self-contained Chrome content script

I've encountered a challenging issue that despite my numerous attempts to resolve, has left me feeling completely stuck. I have exhausted all resources and solutions available... The Dilemma My current project involves developing a Chrome extension ...

Click event for altering text

Hey there, I'm new to HTML and could really use some assistance. My goal is to create 3 buttons that, when clicked, will change the text displayed next to them. For each button, I've included the following code: <a href="#" onClick="document ...

Is there a cap on how many simultaneous ajax requests can be sent using node.js?

I'm working on a node.js server that needs to make numerous ajax requests to various websites in order to download JSON or HTML code. I want to ensure that my approach is efficient and won't cause any issues, not intending to engage in any form o ...

Animating content through CSS and jQuery to reveal its unfolding effect

Just stumbled upon the amazing quote-expansion animation in the OSX Mail app and I am completely impressed. I am on a mission to bring that same magic to the web (or at least close to it), but unsure if anyone has done something similar yet. A couple of ...

Transform JSON data into XLSX format for all files with a .json extension within the specified directory

Dealing with the challenge of parsing multiple JSON files located in the same directory as the program's executable file, extracting specific elements from these files, and consolidating them into a single Excel file. For instance, there are several ...

Is there a way to extend the TTL expiresAfterSeconds duration?

Currently, I am working on a simple application and my model looks like this: import mongoose from "mongoose"; const urlSchema = new mongoose.Schema( { originalUrl: { type: String, required: true }, longUrl: { type: String, required: t ...

Exporting JSON blend files in Three.js is causing an error that says "Cannot read property 'type' of undefined."

Trying to display the default 3D cube template from Blender v2.74 in Chrome browser, I exported it as json using the threejs v1.4.0 add-on and I'm using Three.js revision 71. Referencing the documentation at , I attempted to load this json model stor ...

What is the best way to delete data from a local storage using an index array?

When I log localStorage.getItem("cartCache"), the output is: {"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"},{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}],"expired":"2017-08-28T03:55:2 ...

The existing session persists when a new user logs in, instead of being destroyed

Security measures will be implemented at a later time Currently, I have a login script that operates in two scenarios. It either returns a message in JSON format, indicating issues such as incorrect login credentials or empty fields, or it initiates a ses ...