Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate accordingly.

This is why I am looking to utilize JSON for dynamic loading.

 Json data={"columns":[["data1",15.8,11.749,50.69,10.167],["labels","Fiserv, Inc.","The Vanguard Group, Inc.","Morgan Stanley Smith Barney","JACKSON NATIONAL LIFE INS CO DEPOSIT"]]}

The labels function properly when using the commented-out multi-dimensional array, but encounter issues with dynamically loaded JSON data.

Javascript Code:

 function setupTopSourcesChart(data) {

if (typeof data === 'undefined' || data === null) {
    console.log("Top Sources Chart not available...");
    return;
}

data = $.parseJSON(data);

var value = [];
$.each(data, function(key, i){
    value.push(data.columns[0]);
});


var labels = data.columns[1];

var chart = c3
        .generate({
            bindto : "#topSources",
            size : {
                height : 180,
                width : 450
            },
            bar : {
                width : 16
            },
            padding : {
                right : 160,
                top : 50
            },
            color : {
                pattern : [ '#008000', '#008000', '#008000', '#008000',
                        '#008000' ]
            },
            data : {
                /*columns : [ [ 'Throughput', data.columns[0][1],
                        data.columns[0][2], data.columns[0][3],
                        data.columns[0][4]] ]*/
                json: value,
                type : 'bar',
                labels : {
                    format : { //This doesnt work. helps to show the label in decimals
                        Throughput : d3.format("$,.1f"),

                    }
                },


                color : function(inColor, data) {
                    var colors = [ '#008000', '#008000', '#008000',
                            '#008000', '#008000' ];
                    if (data.index !== undefined) {
                        return colors[data.index];
                    }

                    return inColor;
                }
            },
            axis : {
                rotated : true,
                x : {
                    type : 'category',
                    show : false,
                },
                y : {
                    show : false,
                    padding : {
                        top : 80
                    }
                }
            },
            tooltip : {
                show : false,
                format : {
                    title : function(x) {
                        return x + 1;
                    },
                    value : function(value, ratio, id) {
                        var format = id === 'data1' ? d3.format(',') : d3
                                .format('$');
                        return format(value);
                    }
                },
                grouped : false
            },
            legend : {
                show : false
            }
        });

}

Answer №1

How about utilizing the amazing feature of c3 charts known as data URL

All you need to do is:

  • Provide a URL that returns JSON data (or simply specify the path to the JSON file)
  • Your code should resemble the following snippet:
c3.generate({
        ...
        data: {
            ...
            url: 'my_url_which_return_json',
            mimeType: 'json',
            labels : {
               format: function (v, id, i, j) { return d3.format(".1f")(v) }
               }
            },
        },
        ...
    });

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

Why does my express POST request result in an empty req.body in Node.js?

After confirming that my data is being passed correctly and the db connection is successful, I am facing an issue with my ajax request. Even though the success callback returns the id, my data seems to not be passing through properly. When attempting to a ...

Is the admin_init hook in Wordpress triggering multiple times?

Encountering an issue on my Wordpress website where admin_init is being called twice has been quite a headache. After deactivating all plugins, I managed to pinpoint the culprit plugin that was causing the problem. Now my dilemma is how to determine the ...

AJAX request experiences significant delays due to MySQL query execution

The issue There is a significant delay in the execution of AJAX requests that involve any database queries. This problem has suddenly emerged without any recent updates to the codebase. Interestingly, if the same query is executed on a webpage directly (e ...

Errors in production arise from building React applications

I am new to using React and recently built a ToDo web app following a tutorial. Everything seemed fine during development, but when I tried to view the production version locally using serve -s build, two errors popped up that were not present before. reac ...

Display a loading animation while waiting for the AJAX response

I am working with a seat chart in SVG format on my website. I want to display a loading gif when a user clicks on a seat, and then hide the loading gif once the AJAX response is returned. However, the code I have written for this functionality is not wor ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Unexpected Results from WordPress Ajax Request

Currently, I am utilizing the snippets plugin in conjunction with Elementor. To implement an ajax function as a snippet, I have set it up like so: add_action( 'wp_ajax_get_slug_from_id', 'get_slug_from_id' ); add_action( 'wp_ajax_n ...

Working with JSON responses in Laravel 4 and Mandrill

Recently, I have been utilizing Laravel (4.2) and its inbuilt Mandrill driver to send emails. However, I am facing a challenge in capturing the response from Mandrill. Below is the code snippet I am using to dispatch the message: Mail::queue('emails ...

Merge two JSON objects together by matching their keys and maintaining the original values

After having two separate JSON objects representing data, I found myself in the position of needing to merge them into one combined result. The initial objects were as follows: passObject = { 'Topic One' : 4, 'Topic Two' : 10, &apos ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

Can different versions of jQuery be loaded simultaneously on a single page?

I am in the process of creating a bookmarklet that will load jQuery if the object is not found. The script will also check for the version of jQuery before loading. Here is how the code looks: (function(){ var myBkl = { loadScript: function( ...

Converting multiple WordPress plugins into a single JSON option

Having a plugin with numerous options, I am utilizing an angular application on the frontend to display them all. In order to store these options in the database as JSON data, I need to ensure that all 10 options are saved within a single row in the wp_opt ...

Assistance needed with sending JSON data to a PHP server using the POST method

I am attempting to transfer JSON data from an HTML form to a PHP server using the POST method. The issue I am encountering is that my code always ends up in the fail block within the callback function. Despite this, the Firebug console (ctrl+shift+J) does ...

Upon clicking, the input texts revert to their original default values

I have a form below that is working as intended, except for one issue. When I click the 'Add' link, the texts in all the textboxes revert to their default values, as shown in the images. How can I resolve this problem? Thank you. before click: ...

What is the best way to combine a string with a variable in sass?

Is there a way to merge a string and a variable in Sass to form a variable name that is already present? $size: "sm"; $button-sm: 1rem; $buttom-md: 1.5rem; body { font-size: $button-#{$size}; } The desired output is: body { font-size: 1r ...

Using JavaScript, append a hidden input field in Yii2 and retrieve it from the controller

Seeking assistance as a newcomer to yii2. I'm looking for help in resolving an issue that has arisen. I'm attempting to add a hidden input field to my form using JavaScript (not linked to a model). Subsequently, when I submit the form, I want to ...

Triggering click events in jQuery/AJAX to replace previous appends

Having some issues with page refreshes after jquery click events. This content is loaded dynamically via ajax, so it's not initially present on the page. I'm using ajax to fetch a json array and add it to select dropdowns. When one button is c ...