Как получить круговую диаграмму с помощью jquery, читая CSV-файлы - PullRequest
0 голосов
/ 04 ноября 2019

Пожалуйста, ознакомьтесь с кодом ниже. Я получаю площадь, гистограмму, линейную диаграмму, но с тем же кодом, что я не получил круговую диаграмму.

<?php session_start(); 
if(isset($_SESSION['user_id'])){
    if(isset($_POST['update'])){
        $report_id=$_POST['report_id'];
    }else{
        $report_id=$_GET['report_id'];
    }
    include "header.php";
    include "sidebar.php";
    include 'automation_db_connect.php';
    $chart_type = "";
    $chart_csv = "";
    $chart_values = array();
    $chart_colors = array();
    $subsection_id = 0;
    if(isset($_GET['chart_id'])){
        $chart_id = $_GET['chart_id'];
        $show_chart_sql="SELECT * FROM charts WHERE chart_id=$chart_id";
        $show_chart_result = $conn->query($show_chart_sql);
        if($show_chart_result->num_rows > 0){
            while($chart = $show_chart_result->fetch_assoc()){
                $chart_type = $chart['chart_type'];
                $chart_csv = $chart['chart_csv'];
                $subsection_id = $chart['section_id'];
            }
        }
    }else if(isset($_POST['chart_id'])){
        $chart_id = $_POST['chart_id'];
        $report_id=$_POST['report_id'];
        $chart_type = $_POST['type'];
        $subsection_id = $_POST['subsection_id'];
        $chart_values = $_POST['value'];
        $chart_colors = $_POST['color'];
        $target .= "charts";
        $file_name = "/draft";
        $ext=".csv";
        $target.="$file_name$chart_id$ext";
        $csvfile = fopen($target,'w');
        foreach( $chart_values as $index=>$value )
        {
            if( $index === 0 )
            {
                $table_headers = array("Headers");
                $table_headers = array_merge($table_headers,$value);
                fputcsv($csvfile, $table_headers ); // First write the headers
            }else{
                fputcsv($csvfile, $value ); 
            }
        }
        $color_headers = array("Select Color");
        $color_headers = array_merge($color_headers,$chart_colors);
        fputcsv($csvfile, $color_headers ); // First write the headers
        fclose($csvfile);
        $chart_csv = $target;
    }
    if(empty($chart_csv)){ ?>
    <script>
        alert("Unable to edit the chart. Please delete and recreate it");
    window.location.replace("add_charts.php?report_id=<?php echo $report_id ; ?>");
    </script>
<?php }
$csv_file = fopen($chart_csv,'r');
$k=0;
$color =false;
while (($data = fgetcsv($csv_file, 1000, ",")) !== FALSE) { // Check opening the file is OK
    $j=0;
    for ($i = 0; $i < count($data); $i++) { // Loop over the data using $i as index pointer
        if($data[$i] == "Headers"){
            $j++;
            continue;
        }
        if($data[$i] == "Select Color"){
            $color = true;
            $j++;
            continue;
        }
        if($color == true){
            $chart_colors[$j]=$data[$i];
        }else{
            $chart_values[$k][$j]=$data[$i];
        }
        $j++;
    }
    $k++;
}
fclose($csv_file);
?>
        <style>
        #chart-area ul {
    list-style: none;
}
#chart-area ul li {
    display: block;
    padding-left: 30px;
    position: relative;
    margin-bottom: 4px;
    border-radius: 5px;
    padding: 2px 8px 2px 28px;
    font-size: 14px;
    cursor: default;
    height:20px;
    width: 140px;
    -webkit-transition: background-color 200ms ease-in-out;
    -moz-transition: background-color 200ms ease-in-out;
    -o-transition: background-color 200ms ease-in-out;
    transition: background-color 200ms ease-in-out;
}
#chart-area li span {
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    width: 20px;
    border-radius: 5px;
    height:20px
}

#chart-area li span.line-legend-text {
    left:25px;
    width:120px;
}
#chart-area > *{
    float:left
        }
        .tableFixHead thead th {
        position: sticky;
        top: 0;
        background-color:#ffffff;
        }
        .tableFixHead tfoot th {
        position: sticky;
        bottom: 0;
        background-color:#ffffff;
        }
        .tableFixHead tfoot td {
        position: sticky;
        bottom: 0;
        background-color:#ffffff;
        }
        </style>
        <div class="content-wrapper">
        <!-- Content Header (Page header) -->
                <section class="content-header">
                <h1>
                Charts
                </h1>
                <ol class="breadcrumb">
                        <li class="active"><a href="account.php"><i class="fa fa-dashboard"></i> Home</a></li>
                        <li class="active"><i class="fa fa-pie-chart"></i>Charts</li>
                </ol>
                </section>
                <section class="content">
                        <div class="box box-primary">
                                <div class="box-body">
                                    <?php print_r($chart_values);?>
                                        <div class="chart" id="chart-area">
                                                <canvas id="created_chart" style="background-color:#fff;height:300px"><div id="chart-legends"></div></canvas>
                                                <div id="legend"></div>
                                        </div>
                                </div>
                        <!-- /.box-body -->
                                <div class="box-footer clearfix no-border">
                                    <button id="edit_chart" class="btn btn-default pull-left"><i class="fa fa-pencil" ></i> Edit Chart</button>
                                    <input type="hidden" id="chart_png">
                                    <button id="chart_download" class="btn btn-default pull-right"><i class="fa fa-download" ></i> Save Chart</button>
                                </div>
                        </div>
                        <!-- Edit Chart Area -->
                        <div class="box box-primary">
                        <form action="show-chart.php" class="form-horizontal" method="post" enctype="multipart/form-data">
                                <div class="box-body">
                                <input type="hidden" value="<?php echo $chart_id; ?>" name="chart_id">
                                    <input type="hidden" value="<?php echo $report_id; ?>" name="report_id">
                                    <input type="hidden" value="<?php echo $subsection_id; ?>" name="subsection_id">
                                        <!-- Chart type -->
                                        <div class="form-group">
                                        <label for="chart_select" class="col-sm-2 control-label">Select Chart Type :</label>
                                        <div class="col-sm-2">
                                            <select id="chart_select" name="type" class="form-control">
                                                <option value="bar_graph">Bar Graph</option>
                                                <option value="pie_chart">Pie Chart</option>
                                                <option value="area_chart">Area Chart</option>
                                                <option value="line_chart">Line Chart</option>
                                            </select>
                                        </div>
                                    </div>
                                        <div id="edit-area">
                                                <div class="tableFixHead" style="width: 100%;overflow: auto;max-height:350px;" id="table_created">
                                                    <table class="table table-bordered" id="csv-table">
                                                        <?php
                                                        foreach($chart_values as $i=>$each_row){
                                                            if($i == 0){
                                                        ?>
                                                            <thead>
                                                            <tr><th style="width:15%;" scope="col">Headers</th>
                                                        <?php
                                                            }else if($i==1){
                                                        ?>
                                                            <tbody>
                                                            <tr>
                                                        <?php
                                                            }else{
                                                        ?>
                                                            <tr>
                                                        <?php
                                                            }
                                                        ?>

                                                        <?php
                                                            foreach($each_row as $j=>$each_cell){
                                                                if($i==0){
                                                        ?>
                                                                    <th scope="col"><input type="text" class="form-control" name="value[<?php echo $i;?>][<?php echo $j;?>]" value="<?php echo $each_cell ; ?>"></th>
                                                        <?php
                                                                }else{
                                                                    if($j==0){
                                                        ?>
                                                                    <th scope="row"><input type="text" class="form-control" name="value[<?php echo $i;?>][<?php echo $j;?>]" value="<?php echo $each_cell ; ?>"></th>
                                                        <?php
                                                                    }else{
                                                        ?>
                                                                    <td><input type="number" class="form-control"  name="value[<?php echo $i;?>][<?php echo $j;?>]" value="<?php echo $each_cell ; ?>" min="1"></td>
                                                        <?php
                                                                    }
                                                                }
                                                            }
                                                        ?>
                                                        </tr>
                                                        <?php
                                                            if($i == 0){
                                                        ?>  
                                                            </thead>
                                                        <?php
                                                            }

                                                        }
                                                        ?>
                                                    </tbody>
                                                    <tfoot class="select_color">
                                                        <tr><th scope="row">Select Color</th>
                                                            <?php
                                                            foreach($chart_colors as $index=>$colors){
                                                            ?>
                                                                <td><input type="text" class="form-control my-colorpicker1" name="color[<?php echo $index;?>]" value="<?php echo $colors ; ?>"></td>
                                                            <?php
                                                            }
                                                            ?>
                                                        </tr>
                                                    </tfoot>
                                                    </table>                
                                                </div>
                                        </div>

                                </div>
                        <!-- /.box-body -->
                                <div class="box-footer clearfix no-border">
                                    <button id="update_chart" type="submit" name="update" class="btn btn-default pull-right"><i class="fa fa-refresh" ></i> Update</button>
                                </div>
                                </form>
                        </div>
                </section>
        </div>
<?php
include "footer.php";
?>

<script>
$('.my-colorpicker1').colorpicker();
$(function () {
    var ChartCanvas = $('#created_chart').get(0).getContext('2d')
        var chart_values = <?php echo json_encode($chart_values) ; ?>;
    var chart_colors =  <?php echo json_encode($chart_colors) ; ?>;
    var chart_type = <?php echo json_encode($chart_type) ; ?>;
    var ChartData = {};
    $("#chart_select").val(chart_type);
    ChartData.labels = [];
    ChartData.datasets=[];
    $.each(chart_values,function(outer_index,outer_value){
        $.each(outer_value,function(inner_index, inner_value){
            if(inner_index == 0){
                ChartData.labels.push(inner_value);
}
else{
    array_index = inner_index-1;
    if(!ChartData.datasets[array_index]){
        ChartData.datasets[array_index]={};
}
if(outer_index == 0){
    ChartData.datasets[array_index].fillColor=chart_colors[inner_index];
    ChartData.datasets[array_index].strokeColor=chart_colors[inner_index];
    ChartData.datasets[array_index].label=inner_value;
}
else{
    if(!ChartData.datasets[array_index].data){
        ChartData.datasets[array_index].data=[];
}
ChartData.datasets[array_index].data.push(inner_value);
}
}
});
});
var chart       = new Chart(ChartCanvas);
if(chart_type == "area_chart"){
    var ChartOptions = {
    bezierCurve             : true,
        //Number - Tension of the bezier curve between points
        bezierCurveTension      : 0.5,
        maintainAspectRatio     : true,
        showTooltips: false,
        //Boolean - whether to make the chart responsive to window resizing
        responsive              : true ,
        onAnimationComplete: function () {
            var ctx = this.chart.ctx;
            ctx.font = this.scale.font;
            ctx.fillStyle = "#333";
            ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            this.datasets.forEach(function (dataset) {
                dataset.points.forEach(function (points) {
                    ctx.fillText(points.value, points.x+10, points.y);
});
});
$("#legend").html(this.generateLegend());
var url_base64_png = $('#created_chart').get(0).toDataURL('image/png');
$("#chart_png").val( url_base64_png);

}
}
chart.Line(ChartData, ChartOptions);
}

else if(chart_type == "line_chart"){
    var ChartOptions = {
    bezierCurve             : true,
        //Number - Tension of the bezier curve between points
        bezierCurveTension      : 0.5,
        maintainAspectRatio     : true,
        showTooltips: false,
        //Boolean - whether to make the chart responsive to window resizing
        responsive              : true ,
        datasetFill                         : false,
        onAnimationComplete: function () {
            var ctx = this.chart.ctx;
            ctx.font = this.scale.font;
            ctx.fillStyle = "#333";
            ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            this.datasets.forEach(function (dataset) {
                dataset.points.forEach(function (points) {
                    ctx.fillText(points.value, points.x, points.y-5);
});
});
$("#legend").html(this.generateLegend());
var url_base64_png = $('#created_chart').get(0).toDataURL('image/png');
$("#chart_png").val( url_base64_png);
}
}
chart.Line(ChartData, ChartOptions);
}
else if(chart_type == "bar_graph"){
    console.log(ChartData);
    var ChartOptions = {
    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
    scaleBeginAtZero        : true,
        responsive              : true,
        maintainAspectRatio     : true,
        showTooltips: false,
        onAnimationComplete: function () {
            var ctx = this.chart.ctx;
            ctx.font = this.scale.font;
            ctx.fillStyle = "#333"
                ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            this.datasets.forEach(function (dataset) {
                dataset.bars.forEach(function (points) {
                    ctx.fillText(points.value, points.x, points.y);
});
});
$("#legend").html(this.generateLegend());
var url_base64_png = $('#created_chart').get(0).toDataURL('image/png');
$("#chart_png").val( url_base64_png);
}

}
chart.Bar(ChartData, ChartOptions);
}
/* Adding  Pie Chart functionality */
else if(chart_type == "pie_chart"){
    console.log(ChartData);
    var ChartOptions = {
    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
    scaleBeginAtZero        : true,
        responsive              : true,
        maintainAspectRatio     : true,
        showTooltips: false,
        onAnimationComplete: function () {
            var ctx = this.chart.ctx;
            ctx.font = this.scale.font;
            ctx.fillStyle = "#333"
                ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            this.datasets.forEach(function (dataset) {
                dataset.pie.forEach(function (points) {
                    ctx.fillText(points.value, points.x, points.y);
});
});
$("#legend").html(this.generateLegend());
var url_base64_png = $('#created_chart').get(0).toDataURL('image/png');
$("#chart_png").val( url_base64_png);
}
}
//chart.Doughnut(ChartData, ChartOptions);
chart.Pie(ChartData, ChartOptions);

}
})


    $("#chart_download").click(function(){
        var dataURL = $("#chart_png").val();
        var chart_type = $("#chart_select").val();
        var chart_id = $("input[name=chart_id]").val();
        var report_id = $("input[name=report_id]").val();
        $.post("download-graph.php",{img : dataURL,chart_type : chart_type,chart_id:chart_id},function(data){
            if(data == "Success"){
                alert("Saved Successfully");
                window.location.replace("add_charts.php?report_id="+report_id);
} 
else{
    alert("Unable to convert it to image");
}
});
});
$("#edit_chart").click(function(){
});
</script>

<?php  }else{
include "session_expired.php";
}
?>

здесь я не получаю круговую диаграмму

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...