How to pass the return (JSON) of a getJson request within the date where the chart values will be?

Asked

Viewed 179 times

3

works as follows, has a . js that have the graphics assembled, but with the values inserted directly, I’m having a hard time finding content that fits directly into this example that I’m using, I need a following, be it for $.ajax, getJson, whatever, pass the values of a JSON into the date field:[ 50,100,50];

A part of the code where the graph forms:

   var widgetTechnologiesChart = function() {


    $.getJSON("./func/dash/grafico-dash.php", "valor1", function( data ) {
        console.log(data);
    });

    if ($('#kt_widget_technologies_chart').length == 0) {
        return;
    }

    var randomScalingFactor = function() {
        return Math.round(Math.random() * 100);
    };

    var config = {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [ 
                    50,100,50
                ],
                backgroundColor: [
                    KTApp.getBaseColor('shape', 3),
                    KTApp.getBaseColor('shape', 4),
                    KTApp.getStateColor('brand')
                ]
            }],
            labels: [
                'OHSENHOR',
                'OWDEUS',
                'MEAJUDAAA'
            ]
        },
        options: {
            cutoutPercentage: 75,
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                display: false,
                position: 'top',
            },
            title: {
                display: false,
                text: 'OHGLORIA'
            },
            animation: {
                animateScale: true,
                animateRotate: true
            },
            tooltips: {
                enabled: true,
                intersect: false,
                mode: 'nearest',
                bodySpacing: 5,
                yPadding: 10,
                xPadding: 10, 
                caretPadding: 0,
                displayColors: false,
                backgroundColor: KTApp.getStateColor('brand'),
                titleFontColor: '#ffffff', 
                cornerRadius: 4,
                footerSpacing: 0,
                titleSpacing: 0
            }
        }
    };

    var ctx = document.getElementById('kt_widget_technologies_chart').getContext('2d');
    var myDoughnut = new Chart(ctx, config);
}

And so, I did a lot of research before I got here, but I didn’t find anything that could add me up, and the funny thing is that this code that I posted, if I play it complete even within the proper tag in php it doesn’t render the graph, being that it’s based on Chartjs, Does anyone know how I handle this situation? I tried to use $.getJSON, but it didn’t work, so I just left it in the code as an example of the last thing I tried to use.

The return of json:

{ "Valor1": 50 }{ "Valor2": 80 }

1 answer

3


If you explicitly need return data from JSON, encapsulate your logic "in this return":

var widgetTechnologiesChart = function() {

    if ($('#kt_widget_technologies_chart').length == 0) {
        return;
    }

    var randomScalingFactor = function() {
        return Math.round(Math.random() * 100);
    };
    
    $.getJSON("./func/dash/grafico-dash.php", "valor1", function( jsondata ) {
        var config = {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [
                        50,100,50
                    ],
                    backgroundColor: [
                        KTApp.getBaseColor('shape', 3),
                        KTApp.getBaseColor('shape', 4),
                        KTApp.getStateColor('brand')
                    ]
                }],
                labels: [
                    'OHSENHOR',
                    'OWDEUS',
                    'MEAJUDAAA'
                ]
            },
            options: {
                cutoutPercentage: 75,
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: false,
                    position: 'top',
                },
                title: {
                    display: false,
                    text: 'OHGLORIA'
                },
                animation: {
                    animateScale: true,
                    animateRotate: true
                },
                tooltips: {
                    enabled: true,
                    intersect: false,
                    mode: 'nearest',
                    bodySpacing: 5,
                    yPadding: 10,
                    xPadding: 10,
                    caretPadding: 0,
                    displayColors: false,
                    backgroundColor: KTApp.getStateColor('brand'),
                    titleFontColor: '#ffffff',
                    cornerRadius: 4,
                    footerSpacing: 0,
                    titleSpacing: 0
                }
            }
        };

        var ctx = document.getElementById('kt_widget_technologies_chart').getContext('2d');
        var myDoughnut = new Chart(ctx, config);
    });
}

If the return data JSON (now a Object) you want to use is a Array, use the operator Spread to add them to the matrix:

data: [50, 100, 50, ...jsondata]

Now, if you have to go through or iterate on this return JSON to find values, use the method .push() to add each item to the end of the target matrix (bad date), do this before using the variable "config":

$.getJSON("./func/dash/grafico-dash.php", "valor1", function( jsondata ) {
    var config = {
        data: {
            datasets: [{
                data: [
                    50,100,50
                ],
                backgroundColor: []
            }],
            labels: []
        }
    };

    // faça aqui sua iteração e adicione os novos itens a matriz
    config.data.datasets[0]['data'].push(novo_item)

    var ctx = document.getElementById('kt_widget_technologies_chart').getContext('2d');
    var myDoughnut = new Chart(ctx, config);
});


Editing:

If you need this return you must encapsulate the resulting code because the method $.getJSON() make a request "asynchronous" that is, you must wait for the data to return in order to use it in the rest of the code.

If you want to use this return outside the function you must "previously declare a variable in a higher scope" to be able to use this return to it ... so you can use (with due care) this return in other subsequent parts.

Example:

var retornoJSON

$.getJSON("./func/dash/grafico-dash.php", "valor1", function( jsondata ) {

    // atribuir a variável pré-existente
    retornoJSON = jsondata

    var config = {
        data: {
            datasets: [{
                data: [
                    50,100,50
                ],
                backgroundColor: []
            }],
            labels: []
        }
    };

    // faça aqui sua iteração e adicione os novos itens a matriz
    config.data.datasets[0]['data'].push(novo_item)

    var ctx = document.getElementById('kt_widget_technologies_chart').getContext('2d');
    var myDoughnut = new Chart(ctx, config);
});

/**
 * Em outra parte subsequente mas não linear você pode usar este retorno
 * por exemplo em uma iteração/gesto do usuário ... aqui cabe sua necessidade (criatividade)
 */

 $('#btnShow').on('click', function() {
    if ( retornoJSON !== undefined ) {
        // faça algo com os dados
    }
 });

Issue 2:

Given the following return value JSON (that I believe is in a matrix?):

{ "Valor1": 50 }{ "Valor2": 80 }

You must iterate after declaring the Object "config" and before using it, as follows:

$.getJSON("./func/dash/grafico-dash.php", "valor1", function( jsondata ) {

    /**
     * assumindo que o retorno seja uma matriz [{ "Valor1": 50 },{ "Valor2": 80 }]
     */

    var config = {
        data: {
            datasets: [{
                data: [
                    50,100,50
                ],
                backgroundColor: []
            }],
            labels: []
        }
    };

    /**
     * itere sobre a matriz de retorno `Array` e obtenha o valor dos objetos
     * o uso de `Object.values()` ire retornar uma matriz, dado seu exemplo basta apenas pegar
     * o primeiro índice (nesse caso 0)
     */
    for (let i = 0; i < jsondata.length; i++) {
         config.data.datasets[0]['data'].push(Object.values(jsondata[i])[0])
     }

    var ctx = document.getElementById('kt_widget_technologies_chart').getContext('2d');
    var myDoughnut = new Chart(ctx, config);
});


References:

https://api.jquery.com/jQuery.getJSON/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • Lauro, thank you very much for the help, I understood about the functions above, I tried to use the date: [50, 100, 50, ...jsondata] but when it comes to loading the chart it does not carry the value returned by json, I need that instead of leaving the predefined values, it only pulls the values that json returns: Example: JSON { "valor1": "7039" }{ "valor2": "8150" } Would it be in some of the above forms? or otherwise? Excuse my ignorance :/

  • Yes, in this case you must iterate and add the matrix the value of each object you want

  • Is there a way you can show me a practical example in code? I am very raw in js :/

  • Edit your question by adding a minimal example of what comes back from this json and what you want to use from it. I edit my reply with an iteration example using this return

  • Okay, I put what my json returns.

  • @Antoniodvino, edited response. Give feedback when possible

  • Lauro, without words, you helped me very, very much, I am immensely grateful that you helped me! I’ve been hitting my head with this for days, intendendo now in practice how it works, I think I’ll be able to solve some impasses, thank you very much man! You are a beast, you should teach face because you explained detail by detail, I was very lay that I caught, but you helped me a lot! Thanks! <3

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.