Chart to update from a drop down selection

I have a javascript file app.js and a php file data.php.

app.js creates a graph using data from the JSON output ofdata.php.

See app.jsbelow:

$(document).ready(function(){

  $.ajax({
    url: "http://localhost/chartjs/data.php",
    method: "GET",
    success: function(data) {
      console.log(data);
      var op1 = [];
      var op2 = [];

      let data_keys = Object.keys(data[0])
      console.log(data_keys)
      first = data_keys[0] //1st element
      second = data_keys[1] //2nd element

       for(var i in data) {
            op1.push(data[i][first])
            op2.push(data[i][second])

               }

      var chartdata = {
        labels: op1,
        datasets : [
          {
            label: 'SystemID and Apparent Power (VA)',
            backgroundColor: 'rgba(250, 50, 50, 0.4)',
            borderColor: 'rgba(500, 50, 50, 0.5)',
            hoverBackgroundColor: 'rgba(500, 30, 30, 0.2)',
            hoverBorderColor: 'rgba(500, 30, 30, 0.3)',
            data: op2
          } 
        ]
      };

      var ctx = document.getElementById('mycanvas').getContext('2d');

      var barGraph = new Chart(ctx, {
        type: 'line',
        data: chartdata,
        options: {
        scales: {
           xAxes: [{
                   ticks: {
                    fontSize: 10
                   }
                  }],
            yAxes: [{
                ticks: {
                    fontSize: 10
                }
            }]
                }
             }
      });
    },
    error: function(data) {
      console.log(data);
    }
  });
});

The code above is all working fine, I am able to see a graph using the queried data from my data.php.

Part of data.php is as follows:

$sql = "SELECT SystemID, ApparentPower FROM RaritanMachineDataa";
$result = sqlsrv_query($conn, $sql);
$data = array(); 
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    $row = preg_replace("/[^0-9]/", "", $row);
    $data[] = $row;
}
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
echo json_encode($data);
?>

Now I want to have a drop down menu below my graph and I want to be able to choose from any of the options and send these options to my data.php SELECT query and update the graph. How do I go about doing this?

Answers:

Answer

You can use addData and removeData, see https://www.chartjs.org/docs/latest/developers/updates.html. addData adds only one dataset per call, but removeData removes all datasets from chart. There is also way to push label and dataset see codepen sample: https://codepen.io/jordanwillis/pen/bqaGRR.

First what you need is to save your chart in variable, so you can easy add and remove data. when you have chart saved in var, let's say myChart, you can call removeData() like: myChart.removeData(). For adding data you have to send label and data like: myChart.addData('news', [2, 32, 3]).

The idea is next, to update chart when your ajax call is success. The important thing is to have chart instance in same file where you have ajax call, you should move onclick call to js file, or call function from from àpp.js.

Now depends on your data structure, you will need to go through each and get value and label. You have to get same result from data like you have when you're creating chart.

CODE SAMPLE:

What you will have in app.js

$(document).ready(function(){

    $.ajax({
        url: "http://localhost/chartjs/data.php",
        method: "GET",
        success: function(data) {
            console.log(data);
            var op1 = [];
            var op2 = [];

            let data_keys = Object.keys(data[0])
            console.log(data_keys)
            first = data_keys[0] //1st element
            second = data_keys[1] //2nd element

            for(var i in data) {
                op1.push(data[i][first])
                op2.push(data[i][second])

            }

         var chartdata = {
         labels: op1,
         datasets : [
             {
             label: 'SystemID and Apparent Power (VA)',
             backgroundColor: 'rgba(250, 50, 50, 0.4)',
             borderColor: 'rgba(500, 50, 50, 0.5)',
             hoverBackgroundColor: 'rgba(500, 30, 30, 0.2)',
             hoverBorderColor: 'rgba(500, 30, 30, 0.3)',
             data: op2
         } 
         ]
  };

  var ctx = document.getElementById('mycanvas').getContext('2d');

  var barGraph = new Chart(ctx, {
    type: 'line',
    data: chartdata,
    options: {
    scales: {
       xAxes: [{
               ticks: {
                fontSize: 10
               }
              }],
        yAxes: [{
            ticks: {
                fontSize: 10
            }
        }]
            }
         }
      });
    },
    error: function(data) {
    console.log(data);
    }
    });

    function updateChartAjaxCall(data1, data2)
    {
        //ajax call here 
        $.ajax({
            type: 'POST',
            url: 'data.php',
            dataType: 'html',
            data: {data1:data1,data2:data2},
            success:function(data){ 
                // here also manipulate data what you get to update chart propertly
                myChart.removeData();
                myChart.addData('newLabel', [23, 33, 4]);
            }, 
            error:function (xhr, ajaxOptions, thrownError){
                console.log(thrownError);
            }, 
            complete: function(){
            }
        });
        e.preventDefault(); 
    }
});

Then you bargraph.html will be also changed:

<script type="text/javascript">

$('#submitButton').click(function(e){
    var data1=$("#data1").val();
    var data2=$("#data2").val();

    updateChartAjaxCall(data1, data2);
});
</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.