简体   繁体   中英

how to get each data from a parseJSON array

I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

<html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript">
    var BASE_URL = "<?php echo base_url(); ?>";
    </script>
 <script type="text/javascript">
  // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

function drawChart() {

     $.ajax({

   type: 'POST',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "json",



    success: function (data1) {
    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('string', 'solid');
  var jsonData = $.parseJSON(data1);

  for (var i = 0; i < jsonData.length; i++) {
        data.addRows([jsonData[i].timeline, jsonData[i].solid_t1]);
  }
  var options = {

    title: 'Solid chart',
    width: 900,
    height: 500,

  };

  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
   }
});
}
  </script>
</head>
<body>

  <div id="line_chart"></div>
</body>
</html>

Here under is the function getdata in my controller:

    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}

I tried to output the json_encode data, and I am able to get the result below:

[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}

Final Update : I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});

This

dataType: "json",

ensures that you are expecting json as response ( documentation here ), so you don't need to do

var jsonData = $.parseJSON(data1);

data1 is already a javascript object

try using this

    $.post(BASE_URL+'index.php/Chart_varnish/getdata',function(data1){
      $.each(data1,function(index,value){
      data.addColumn(value.timeline,value.solid_t1);
         });
//more CODE HERE
    },'JSON');

I hope it will help you solve the problem. you should also want to echo the json like this

echo json_encode($data1);

Assuming the response from the PHP script is JSON data then you could probably process the response data like this.

function drawChart() {
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'index.php/Chart_varnish/getdata',
        dataType: 'json',
        success: function(response) {
            var dataTbl = new google.visualization.DataTable();
                /* a number for at least 1 column is req'd ? */
                dataTbl.addColumn('string', 'timeline');
                dataTbl.addColumn('string', 'solid');

            /* iterate through the response data */
            for( var n in response ){
                if( response[n] && typeof(response[n])=='object' ){
                    dataTbl.addRows( response[n].timeline, response[n].solid_t1 );
                }
            }
            var options = {
                title: 'Solid chart',
                width: 900,
                height: 500,

            };
            var chart = new google.visualization.LineChart( document.getElementById('line_chart') );
                chart.draw( dataTbl, options );
        }
    });
}

The PHP script should simply use json_encode - the second argument can be a bitwise combination of flags ( predefined constants ) rather than a simple true/false - it is the json_decode function that uses /true/false as it's 2nd argument.

function getdata(){
    $this->load->model('Chart');
    $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();

    /* echo rather than print_r */
    echo json_encode( $data );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM