0

I created API to pull data from MySQL. What I'm trying to do is to connect the response (output) of API to Google Chart. The problem is the chart do not display the API response. Any idea how I would go about this?

Here is my code:

// api connection
var request = new XMLHttpRequest()
request.open('POST', 'http://localhost:3000/api', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

var obj
request.onreadystatechange = function() {
    // check api status
    if (this.readyState == 4 && this.status == 200) {

        // response
        obj = JSON.parse(this.responseText)
    }

    // google chart
    google.charts.load("current", {packages:["corechart"]})
    google.charts.setOnLoadCallback(pieChart)

    // piechart function
    function pieChart() {

        // push response
        var pieData = []
        obj.forEach(item => {
            pieData.push([item.title, item.data)]
        })

        // add response to chart
        var data = new google.visualization.DataTable()
        data.addColumn('string', 'Title')
        data.addColumn('string', 'Size')
        data.addRows(pieData)

        var options = {
            title: '',
            is#D: true
        }

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d')
        chart.draw(data, options)
    }
}

Thank you.

ctlt
  • 78
  • 6

1 Answers1

0
function pieChart() {
  $.ajax({
    url: 'http://localhost:3000/graph',
    type: 'post',
    dataType: 'json',
    crossDomain: true,
    success: function(jsonObj) {
      var arr = [
        ['Road Type', 'Size']
      ];
      $.each(jsonObj, function(i, tObj) {
        console.log(tObj)

        arr.push([String(tObj.title), parseFloat(tObj.data)]);

      });
      console.log(arr);
      var data = google.visualization.arrayToDataTable(arr);

      var options = {
        title: '',
        is3D: true
      };

      var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
      chart.draw(data, options);
    }
  });
}

Source: http://jsfiddle.net/K8bk3

double-beep
  • 5,031
  • 17
  • 33
  • 41
ctlt
  • 78
  • 6