Chartjs-Execute chartjs after an ajax call with PHP

1πŸ‘

βœ…

To take the value of variables you have to access the json obtained as an answer (data) and you have to convert β€œval1, val2, …” in the vector [val1, val2, …] with split:

var ctx = document.getElementById("myChart").getContext('2d');
        $.ajax({
            url: "server.php",
            type: "POST",
            data: {
                ...
            },
            success: function(data) {
                var datos = JSON.parse(data);
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: datos.cot_labels.split(','), ///in this way you access the data of the returned json
                        datasets: [{
                            data: datos.cot_values.split(','),///in this way you access the data of the returned json
                            label: "A",
                            borderColor: "#3e95cd",
                            fill: false
                        }, {
                            data: datos.cot_values2.split(','),
                            label: "B",
                            borderColor: "#8e5ea2",
                            fill: false
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: datos.name
                        },
                        animation: {
                            duration: 0, // general animation time
                        },
                        hover: {
                            animationDuration: 0, // duration of animations when hovering an item
                        },
                        responsiveAnimationDuration: 0, // animation duration after a resize
                    }
                });
            }
        });

Result:

Chart Line 1

Chart Line 2

Leave a comment